Expressions
Every AST node in SQLGlot is represented by a subclass of Expression.
This module contains the implementation of all supported Expression types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot.errors import ParseError 25from sqlglot.helper import ( 26 AutoName, 27 camel_to_snake_case, 28 ensure_collection, 29 ensure_list, 30 seq_get, 31 split_num_words, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39E = t.TypeVar("E", bound="Expression") 40 41 42class _Expression(type): 43 def __new__(cls, clsname, bases, attrs): 44 klass = super().__new__(cls, clsname, bases, attrs) 45 46 # When an Expression class is created, its key is automatically set to be 47 # the lowercase version of the class' name. 48 klass.key = clsname.lower() 49 50 # This is so that docstrings are not inherited in pdoc 51 klass.__doc__ = klass.__doc__ or "" 52 53 return klass 54 55 56class Expression(metaclass=_Expression): 57 """ 58 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 59 context, such as its child expressions, their names (arg keys), and whether a given child expression 60 is optional or not. 61 62 Attributes: 63 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 64 and representing expressions as strings. 65 arg_types: determines what arguments (child nodes) are supported by an expression. It 66 maps arg keys to booleans that indicate whether the corresponding args are optional. 67 68 Example: 69 >>> class Foo(Expression): 70 ... arg_types = {"this": True, "expression": False} 71 72 The above definition informs us that Foo is an Expression that requires an argument called 73 "this" and may also optionally receive an argument called "expression". 74 75 Args: 76 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 77 parent: a reference to the parent expression (or None, in case of root expressions). 78 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 79 uses to refer to it. 80 comments: a list of comments that are associated with a given expression. This is used in 81 order to preserve comments when transpiling SQL code. 82 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 83 optimizer, in order to enable some transformations that require type information. 84 """ 85 86 key = "expression" 87 arg_types = {"this": True} 88 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 89 90 def __init__(self, **args: t.Any): 91 self.args: t.Dict[str, t.Any] = args 92 self.parent: t.Optional[Expression] = None 93 self.arg_key: t.Optional[str] = None 94 self.comments: t.Optional[t.List[str]] = None 95 self._type: t.Optional[DataType] = None 96 self._meta: t.Optional[t.Dict[str, t.Any]] = None 97 self._hash: t.Optional[int] = None 98 99 for arg_key, value in self.args.items(): 100 self._set_parent(arg_key, value) 101 102 def __eq__(self, other) -> bool: 103 return type(self) is type(other) and hash(self) == hash(other) 104 105 @property 106 def hashable_args(self) -> t.Any: 107 args = (self.args.get(k) for k in self.arg_types) 108 109 return tuple( 110 (tuple(_norm_arg(a) for a in arg) if arg else None) 111 if type(arg) is list 112 else (_norm_arg(arg) if arg is not None and arg is not False else None) 113 for arg in args 114 ) 115 116 def __hash__(self) -> int: 117 if self._hash is not None: 118 return self._hash 119 120 return hash((self.__class__, self.hashable_args)) 121 122 @property 123 def this(self): 124 """ 125 Retrieves the argument with key "this". 126 """ 127 return self.args.get("this") 128 129 @property 130 def expression(self): 131 """ 132 Retrieves the argument with key "expression". 133 """ 134 return self.args.get("expression") 135 136 @property 137 def expressions(self): 138 """ 139 Retrieves the argument with key "expressions". 140 """ 141 return self.args.get("expressions") or [] 142 143 def text(self, key) -> str: 144 """ 145 Returns a textual representation of the argument corresponding to "key". This can only be used 146 for args that are strings or leaf Expression instances, such as identifiers and literals. 147 """ 148 field = self.args.get(key) 149 if isinstance(field, str): 150 return field 151 if isinstance(field, (Identifier, Literal, Var)): 152 return field.this 153 if isinstance(field, (Star, Null)): 154 return field.name 155 return "" 156 157 @property 158 def is_string(self) -> bool: 159 """ 160 Checks whether a Literal expression is a string. 161 """ 162 return isinstance(self, Literal) and self.args["is_string"] 163 164 @property 165 def is_number(self) -> bool: 166 """ 167 Checks whether a Literal expression is a number. 168 """ 169 return isinstance(self, Literal) and not self.args["is_string"] 170 171 @property 172 def is_int(self) -> bool: 173 """ 174 Checks whether a Literal expression is an integer. 175 """ 176 if self.is_number: 177 try: 178 int(self.name) 179 return True 180 except ValueError: 181 pass 182 return False 183 184 @property 185 def is_star(self) -> bool: 186 """Checks whether an expression is a star.""" 187 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 188 189 @property 190 def alias(self) -> str: 191 """ 192 Returns the alias of the expression, or an empty string if it's not aliased. 193 """ 194 if isinstance(self.args.get("alias"), TableAlias): 195 return self.args["alias"].name 196 return self.text("alias") 197 198 @property 199 def name(self) -> str: 200 return self.text("this") 201 202 @property 203 def alias_or_name(self): 204 return self.alias or self.name 205 206 @property 207 def output_name(self): 208 """ 209 Name of the output column if this expression is a selection. 210 211 If the Expression has no output name, an empty string is returned. 212 213 Example: 214 >>> from sqlglot import parse_one 215 >>> parse_one("SELECT a").expressions[0].output_name 216 'a' 217 >>> parse_one("SELECT b AS c").expressions[0].output_name 218 'c' 219 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 220 '' 221 """ 222 return "" 223 224 @property 225 def type(self) -> t.Optional[DataType]: 226 return self._type 227 228 @type.setter 229 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 230 if dtype and not isinstance(dtype, DataType): 231 dtype = DataType.build(dtype) 232 self._type = dtype # type: ignore 233 234 @property 235 def meta(self) -> t.Dict[str, t.Any]: 236 if self._meta is None: 237 self._meta = {} 238 return self._meta 239 240 def __deepcopy__(self, memo): 241 copy = self.__class__(**deepcopy(self.args)) 242 if self.comments is not None: 243 copy.comments = deepcopy(self.comments) 244 245 if self._type is not None: 246 copy._type = self._type.copy() 247 248 if self._meta is not None: 249 copy._meta = deepcopy(self._meta) 250 251 return copy 252 253 def copy(self): 254 """ 255 Returns a deep copy of the expression. 256 """ 257 new = deepcopy(self) 258 new.parent = self.parent 259 return new 260 261 def append(self, arg_key, value): 262 """ 263 Appends value to arg_key if it's a list or sets it as a new list. 264 265 Args: 266 arg_key (str): name of the list expression arg 267 value (Any): value to append to the list 268 """ 269 if not isinstance(self.args.get(arg_key), list): 270 self.args[arg_key] = [] 271 self.args[arg_key].append(value) 272 self._set_parent(arg_key, value) 273 274 def set(self, arg_key, value): 275 """ 276 Sets `arg_key` to `value`. 277 278 Args: 279 arg_key (str): name of the expression arg. 280 value: value to set the arg to. 281 """ 282 self.args[arg_key] = value 283 self._set_parent(arg_key, value) 284 285 def _set_parent(self, arg_key, value): 286 if hasattr(value, "parent"): 287 value.parent = self 288 value.arg_key = arg_key 289 elif type(value) is list: 290 for v in value: 291 if hasattr(v, "parent"): 292 v.parent = self 293 v.arg_key = arg_key 294 295 @property 296 def depth(self): 297 """ 298 Returns the depth of this tree. 299 """ 300 if self.parent: 301 return self.parent.depth + 1 302 return 0 303 304 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 305 """Yields the key and expression for all arguments, exploding list args.""" 306 for k, vs in self.args.items(): 307 if type(vs) is list: 308 for v in vs: 309 if hasattr(v, "parent"): 310 yield k, v 311 else: 312 if hasattr(vs, "parent"): 313 yield k, vs 314 315 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 316 """ 317 Returns the first node in this tree which matches at least one of 318 the specified types. 319 320 Args: 321 expression_types: the expression type(s) to match. 322 323 Returns: 324 The node which matches the criteria or None if no such node was found. 325 """ 326 return next(self.find_all(*expression_types, bfs=bfs), None) 327 328 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 329 """ 330 Returns a generator object which visits all nodes in this tree and only 331 yields those that match at least one of the specified expression types. 332 333 Args: 334 expression_types: the expression type(s) to match. 335 336 Returns: 337 The generator object. 338 """ 339 for expression, *_ in self.walk(bfs=bfs): 340 if isinstance(expression, expression_types): 341 yield expression 342 343 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 344 """ 345 Returns a nearest parent matching expression_types. 346 347 Args: 348 expression_types: the expression type(s) to match. 349 350 Returns: 351 The parent node. 352 """ 353 ancestor = self.parent 354 while ancestor and not isinstance(ancestor, expression_types): 355 ancestor = ancestor.parent 356 return t.cast(E, ancestor) 357 358 @property 359 def parent_select(self): 360 """ 361 Returns the parent select statement. 362 """ 363 return self.find_ancestor(Select) 364 365 @property 366 def same_parent(self): 367 """Returns if the parent is the same class as itself.""" 368 return type(self.parent) is self.__class__ 369 370 def root(self) -> Expression: 371 """ 372 Returns the root expression of this tree. 373 """ 374 expression = self 375 while expression.parent: 376 expression = expression.parent 377 return expression 378 379 def walk(self, bfs=True, prune=None): 380 """ 381 Returns a generator object which visits all nodes in this tree. 382 383 Args: 384 bfs (bool): if set to True the BFS traversal order will be applied, 385 otherwise the DFS traversal will be used instead. 386 prune ((node, parent, arg_key) -> bool): callable that returns True if 387 the generator should stop traversing this branch of the tree. 388 389 Returns: 390 the generator object. 391 """ 392 if bfs: 393 yield from self.bfs(prune=prune) 394 else: 395 yield from self.dfs(prune=prune) 396 397 def dfs(self, parent=None, key=None, prune=None): 398 """ 399 Returns a generator object which visits all nodes in this tree in 400 the DFS (Depth-first) order. 401 402 Returns: 403 The generator object. 404 """ 405 parent = parent or self.parent 406 yield self, parent, key 407 if prune and prune(self, parent, key): 408 return 409 410 for k, v in self.iter_expressions(): 411 yield from v.dfs(self, k, prune) 412 413 def bfs(self, prune=None): 414 """ 415 Returns a generator object which visits all nodes in this tree in 416 the BFS (Breadth-first) order. 417 418 Returns: 419 The generator object. 420 """ 421 queue = deque([(self, self.parent, None)]) 422 423 while queue: 424 item, parent, key = queue.popleft() 425 426 yield item, parent, key 427 if prune and prune(item, parent, key): 428 continue 429 430 for k, v in item.iter_expressions(): 431 queue.append((v, item, k)) 432 433 def unnest(self): 434 """ 435 Returns the first non parenthesis child or self. 436 """ 437 expression = self 438 while type(expression) is Paren: 439 expression = expression.this 440 return expression 441 442 def unalias(self): 443 """ 444 Returns the inner expression if this is an Alias. 445 """ 446 if isinstance(self, Alias): 447 return self.this 448 return self 449 450 def unnest_operands(self): 451 """ 452 Returns unnested operands as a tuple. 453 """ 454 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 455 456 def flatten(self, unnest=True): 457 """ 458 Returns a generator which yields child nodes who's parents are the same class. 459 460 A AND B AND C -> [A, B, C] 461 """ 462 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 463 if not type(node) is self.__class__: 464 yield node.unnest() if unnest else node 465 466 def __str__(self): 467 return self.sql() 468 469 def __repr__(self): 470 return self._to_s() 471 472 def sql(self, dialect: DialectType = None, **opts) -> str: 473 """ 474 Returns SQL string representation of this tree. 475 476 Args: 477 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 478 opts: other `sqlglot.generator.Generator` options. 479 480 Returns: 481 The SQL string. 482 """ 483 from sqlglot.dialects import Dialect 484 485 return Dialect.get_or_raise(dialect)().generate(self, **opts) 486 487 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 488 indent = "" if not level else "\n" 489 indent += "".join([" "] * level) 490 left = f"({self.key.upper()} " 491 492 args: t.Dict[str, t.Any] = { 493 k: ", ".join( 494 v._to_s(hide_missing=hide_missing, level=level + 1) 495 if hasattr(v, "_to_s") 496 else str(v) 497 for v in ensure_list(vs) 498 if v is not None 499 ) 500 for k, vs in self.args.items() 501 } 502 args["comments"] = self.comments 503 args["type"] = self.type 504 args = {k: v for k, v in args.items() if v or not hide_missing} 505 506 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 507 right += ")" 508 509 return indent + left + right 510 511 def transform(self, fun, *args, copy=True, **kwargs): 512 """ 513 Recursively visits all tree nodes (excluding already transformed ones) 514 and applies the given transformation function to each node. 515 516 Args: 517 fun (function): a function which takes a node as an argument and returns a 518 new transformed node or the same node without modifications. If the function 519 returns None, then the corresponding node will be removed from the syntax tree. 520 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 521 modified in place. 522 523 Returns: 524 The transformed tree. 525 """ 526 node = self.copy() if copy else self 527 new_node = fun(node, *args, **kwargs) 528 529 if new_node is None or not isinstance(new_node, Expression): 530 return new_node 531 if new_node is not node: 532 new_node.parent = node.parent 533 return new_node 534 535 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 536 return new_node 537 538 def replace(self, expression): 539 """ 540 Swap out this expression with a new expression. 541 542 For example:: 543 544 >>> tree = Select().select("x").from_("tbl") 545 >>> tree.find(Column).replace(Column(this="y")) 546 (COLUMN this: y) 547 >>> tree.sql() 548 'SELECT y FROM tbl' 549 550 Args: 551 expression (Expression|None): new node 552 553 Returns: 554 The new expression or expressions. 555 """ 556 if not self.parent: 557 return expression 558 559 parent = self.parent 560 self.parent = None 561 562 replace_children(parent, lambda child: expression if child is self else child) 563 return expression 564 565 def pop(self): 566 """ 567 Remove this expression from its AST. 568 569 Returns: 570 The popped expression. 571 """ 572 self.replace(None) 573 return self 574 575 def assert_is(self, type_): 576 """ 577 Assert that this `Expression` is an instance of `type_`. 578 579 If it is NOT an instance of `type_`, this raises an assertion error. 580 Otherwise, this returns this expression. 581 582 Examples: 583 This is useful for type security in chained expressions: 584 585 >>> import sqlglot 586 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 587 'SELECT x, z FROM y' 588 """ 589 assert isinstance(self, type_) 590 return self 591 592 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 593 """ 594 Checks if this expression is valid (e.g. all mandatory args are set). 595 596 Args: 597 args: a sequence of values that were used to instantiate a Func expression. This is used 598 to check that the provided arguments don't exceed the function argument limit. 599 600 Returns: 601 A list of error messages for all possible errors that were found. 602 """ 603 errors: t.List[str] = [] 604 605 for k in self.args: 606 if k not in self.arg_types: 607 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 608 for k, mandatory in self.arg_types.items(): 609 v = self.args.get(k) 610 if mandatory and (v is None or (isinstance(v, list) and not v)): 611 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 612 613 if ( 614 args 615 and isinstance(self, Func) 616 and len(args) > len(self.arg_types) 617 and not self.is_var_len_args 618 ): 619 errors.append( 620 f"The number of provided arguments ({len(args)}) is greater than " 621 f"the maximum number of supported arguments ({len(self.arg_types)})" 622 ) 623 624 return errors 625 626 def dump(self): 627 """ 628 Dump this Expression to a JSON-serializable dict. 629 """ 630 from sqlglot.serde import dump 631 632 return dump(self) 633 634 @classmethod 635 def load(cls, obj): 636 """ 637 Load a dict (as returned by `Expression.dump`) into an Expression instance. 638 """ 639 from sqlglot.serde import load 640 641 return load(obj) 642 643 644IntoType = t.Union[ 645 str, 646 t.Type[Expression], 647 t.Collection[t.Union[str, t.Type[Expression]]], 648] 649ExpOrStr = t.Union[str, Expression] 650 651 652class Condition(Expression): 653 def and_(self, *expressions, dialect=None, **opts): 654 """ 655 AND this condition with one or multiple expressions. 656 657 Example: 658 >>> condition("x=1").and_("y=1").sql() 659 'x = 1 AND y = 1' 660 661 Args: 662 *expressions (str | Expression): the SQL code strings to parse. 663 If an `Expression` instance is passed, it will be used as-is. 664 dialect (str): the dialect used to parse the input expression. 665 opts (kwargs): other options to use to parse the input expressions. 666 667 Returns: 668 And: the new condition. 669 """ 670 return and_(self, *expressions, dialect=dialect, **opts) 671 672 def or_(self, *expressions, dialect=None, **opts): 673 """ 674 OR this condition with one or multiple expressions. 675 676 Example: 677 >>> condition("x=1").or_("y=1").sql() 678 'x = 1 OR y = 1' 679 680 Args: 681 *expressions (str | Expression): the SQL code strings to parse. 682 If an `Expression` instance is passed, it will be used as-is. 683 dialect (str): the dialect used to parse the input expression. 684 opts (kwargs): other options to use to parse the input expressions. 685 686 Returns: 687 Or: the new condition. 688 """ 689 return or_(self, *expressions, dialect=dialect, **opts) 690 691 def not_(self): 692 """ 693 Wrap this condition with NOT. 694 695 Example: 696 >>> condition("x=1").not_().sql() 697 'NOT x = 1' 698 699 Returns: 700 Not: the new condition. 701 """ 702 return not_(self) 703 704 705class Predicate(Condition): 706 """Relationships like x = y, x > 1, x >= y.""" 707 708 709class DerivedTable(Expression): 710 @property 711 def alias_column_names(self): 712 table_alias = self.args.get("alias") 713 if not table_alias: 714 return [] 715 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 716 return [c.name for c in column_list] 717 718 @property 719 def selects(self): 720 alias = self.args.get("alias") 721 722 if alias: 723 return alias.columns 724 return [] 725 726 @property 727 def named_selects(self): 728 return [select.output_name for select in self.selects] 729 730 731class Unionable(Expression): 732 def union(self, expression, distinct=True, dialect=None, **opts): 733 """ 734 Builds a UNION expression. 735 736 Example: 737 >>> import sqlglot 738 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 739 'SELECT * FROM foo UNION SELECT * FROM bla' 740 741 Args: 742 expression (str | Expression): the SQL code string. 743 If an `Expression` instance is passed, it will be used as-is. 744 distinct (bool): set the DISTINCT flag if and only if this is true. 745 dialect (str): the dialect used to parse the input expression. 746 opts (kwargs): other options to use to parse the input expressions. 747 Returns: 748 Union: the Union expression. 749 """ 750 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 751 752 def intersect(self, expression, distinct=True, dialect=None, **opts): 753 """ 754 Builds an INTERSECT expression. 755 756 Example: 757 >>> import sqlglot 758 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 759 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 760 761 Args: 762 expression (str | Expression): the SQL code string. 763 If an `Expression` instance is passed, it will be used as-is. 764 distinct (bool): set the DISTINCT flag if and only if this is true. 765 dialect (str): the dialect used to parse the input expression. 766 opts (kwargs): other options to use to parse the input expressions. 767 Returns: 768 Intersect: the Intersect expression 769 """ 770 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 771 772 def except_(self, expression, distinct=True, dialect=None, **opts): 773 """ 774 Builds an EXCEPT expression. 775 776 Example: 777 >>> import sqlglot 778 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 779 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 780 781 Args: 782 expression (str | Expression): the SQL code string. 783 If an `Expression` instance is passed, it will be used as-is. 784 distinct (bool): set the DISTINCT flag if and only if this is true. 785 dialect (str): the dialect used to parse the input expression. 786 opts (kwargs): other options to use to parse the input expressions. 787 Returns: 788 Except: the Except expression 789 """ 790 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 791 792 793class UDTF(DerivedTable, Unionable): 794 pass 795 796 797class Cache(Expression): 798 arg_types = { 799 "with": False, 800 "this": True, 801 "lazy": False, 802 "options": False, 803 "expression": False, 804 } 805 806 807class Uncache(Expression): 808 arg_types = {"this": True, "exists": False} 809 810 811class Create(Expression): 812 arg_types = { 813 "with": False, 814 "this": True, 815 "kind": True, 816 "expression": False, 817 "exists": False, 818 "properties": False, 819 "replace": False, 820 "unique": False, 821 "volatile": False, 822 "indexes": False, 823 "no_schema_binding": False, 824 "begin": False, 825 } 826 827 828class Describe(Expression): 829 arg_types = {"this": True, "kind": False} 830 831 832class Pragma(Expression): 833 pass 834 835 836class Set(Expression): 837 arg_types = {"expressions": False} 838 839 840class SetItem(Expression): 841 arg_types = { 842 "this": False, 843 "expressions": False, 844 "kind": False, 845 "collate": False, # MySQL SET NAMES statement 846 "global": False, 847 } 848 849 850class Show(Expression): 851 arg_types = { 852 "this": True, 853 "target": False, 854 "offset": False, 855 "limit": False, 856 "like": False, 857 "where": False, 858 "db": False, 859 "full": False, 860 "mutex": False, 861 "query": False, 862 "channel": False, 863 "global": False, 864 "log": False, 865 "position": False, 866 "types": False, 867 } 868 869 870class UserDefinedFunction(Expression): 871 arg_types = {"this": True, "expressions": False, "wrapped": False} 872 873 874class CharacterSet(Expression): 875 arg_types = {"this": True, "default": False} 876 877 878class With(Expression): 879 arg_types = {"expressions": True, "recursive": False} 880 881 @property 882 def recursive(self) -> bool: 883 return bool(self.args.get("recursive")) 884 885 886class WithinGroup(Expression): 887 arg_types = {"this": True, "expression": False} 888 889 890class CTE(DerivedTable): 891 arg_types = {"this": True, "alias": True} 892 893 894class TableAlias(Expression): 895 arg_types = {"this": False, "columns": False} 896 897 @property 898 def columns(self): 899 return self.args.get("columns") or [] 900 901 902class BitString(Condition): 903 pass 904 905 906class HexString(Condition): 907 pass 908 909 910class ByteString(Condition): 911 pass 912 913 914class Column(Condition): 915 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 916 917 @property 918 def table(self) -> str: 919 return self.text("table") 920 921 @property 922 def db(self) -> str: 923 return self.text("db") 924 925 @property 926 def catalog(self) -> str: 927 return self.text("catalog") 928 929 @property 930 def output_name(self) -> str: 931 return self.name 932 933 @property 934 def parts(self) -> t.List[Identifier]: 935 """Return the parts of a column in order catalog, db, table, name.""" 936 return [part for part in reversed(list(self.args.values())) if part] 937 938 def to_dot(self) -> Dot: 939 """Converts the column into a dot expression.""" 940 parts = self.parts 941 parent = self.parent 942 943 while parent: 944 if isinstance(parent, Dot): 945 parts.append(parent.expression) 946 parent = parent.parent 947 948 return Dot.build(parts) 949 950 951class ColumnDef(Expression): 952 arg_types = { 953 "this": True, 954 "kind": False, 955 "constraints": False, 956 "exists": False, 957 } 958 959 960class AlterColumn(Expression): 961 arg_types = { 962 "this": True, 963 "dtype": False, 964 "collate": False, 965 "using": False, 966 "default": False, 967 "drop": False, 968 } 969 970 971class RenameTable(Expression): 972 pass 973 974 975class SetTag(Expression): 976 arg_types = {"expressions": True, "unset": False} 977 978 979class Comment(Expression): 980 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 981 982 983class ColumnConstraint(Expression): 984 arg_types = {"this": False, "kind": True} 985 986 987class ColumnConstraintKind(Expression): 988 pass 989 990 991class AutoIncrementColumnConstraint(ColumnConstraintKind): 992 pass 993 994 995class CaseSpecificColumnConstraint(ColumnConstraintKind): 996 arg_types = {"not_": True} 997 998 999class CharacterSetColumnConstraint(ColumnConstraintKind): 1000 arg_types = {"this": True} 1001 1002 1003class CheckColumnConstraint(ColumnConstraintKind): 1004 pass 1005 1006 1007class CollateColumnConstraint(ColumnConstraintKind): 1008 pass 1009 1010 1011class CommentColumnConstraint(ColumnConstraintKind): 1012 pass 1013 1014 1015class CompressColumnConstraint(ColumnConstraintKind): 1016 pass 1017 1018 1019class DateFormatColumnConstraint(ColumnConstraintKind): 1020 arg_types = {"this": True} 1021 1022 1023class DefaultColumnConstraint(ColumnConstraintKind): 1024 pass 1025 1026 1027class EncodeColumnConstraint(ColumnConstraintKind): 1028 pass 1029 1030 1031class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1032 # this: True -> ALWAYS, this: False -> BY DEFAULT 1033 arg_types = { 1034 "this": False, 1035 "start": False, 1036 "increment": False, 1037 "minvalue": False, 1038 "maxvalue": False, 1039 "cycle": False, 1040 } 1041 1042 1043class InlineLengthColumnConstraint(ColumnConstraintKind): 1044 pass 1045 1046 1047class NotNullColumnConstraint(ColumnConstraintKind): 1048 arg_types = {"allow_null": False} 1049 1050 1051class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1052 arg_types = {"desc": False} 1053 1054 1055class TitleColumnConstraint(ColumnConstraintKind): 1056 pass 1057 1058 1059class UniqueColumnConstraint(ColumnConstraintKind): 1060 arg_types: t.Dict[str, t.Any] = {} 1061 1062 1063class UppercaseColumnConstraint(ColumnConstraintKind): 1064 arg_types: t.Dict[str, t.Any] = {} 1065 1066 1067class PathColumnConstraint(ColumnConstraintKind): 1068 pass 1069 1070 1071class Constraint(Expression): 1072 arg_types = {"this": True, "expressions": True} 1073 1074 1075class Delete(Expression): 1076 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1077 1078 def delete( 1079 self, 1080 table: ExpOrStr, 1081 dialect: DialectType = None, 1082 copy: bool = True, 1083 **opts, 1084 ) -> Delete: 1085 """ 1086 Create a DELETE expression or replace the table on an existing DELETE expression. 1087 1088 Example: 1089 >>> delete("tbl").sql() 1090 'DELETE FROM tbl' 1091 1092 Args: 1093 table: the table from which to delete. 1094 dialect: the dialect used to parse the input expression. 1095 copy: if `False`, modify this expression instance in-place. 1096 opts: other options to use to parse the input expressions. 1097 1098 Returns: 1099 Delete: the modified expression. 1100 """ 1101 return _apply_builder( 1102 expression=table, 1103 instance=self, 1104 arg="this", 1105 dialect=dialect, 1106 into=Table, 1107 copy=copy, 1108 **opts, 1109 ) 1110 1111 def where( 1112 self, 1113 *expressions: ExpOrStr, 1114 append: bool = True, 1115 dialect: DialectType = None, 1116 copy: bool = True, 1117 **opts, 1118 ) -> Delete: 1119 """ 1120 Append to or set the WHERE expressions. 1121 1122 Example: 1123 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1124 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1125 1126 Args: 1127 *expressions: the SQL code strings to parse. 1128 If an `Expression` instance is passed, it will be used as-is. 1129 Multiple expressions are combined with an AND operator. 1130 append: if `True`, AND the new expressions to any existing expression. 1131 Otherwise, this resets the expression. 1132 dialect: the dialect used to parse the input expressions. 1133 copy: if `False`, modify this expression instance in-place. 1134 opts: other options to use to parse the input expressions. 1135 1136 Returns: 1137 Delete: the modified expression. 1138 """ 1139 return _apply_conjunction_builder( 1140 *expressions, 1141 instance=self, 1142 arg="where", 1143 append=append, 1144 into=Where, 1145 dialect=dialect, 1146 copy=copy, 1147 **opts, 1148 ) 1149 1150 def returning( 1151 self, 1152 expression: ExpOrStr, 1153 dialect: DialectType = None, 1154 copy: bool = True, 1155 **opts, 1156 ) -> Delete: 1157 """ 1158 Set the RETURNING expression. Not supported by all dialects. 1159 1160 Example: 1161 >>> delete("tbl").returning("*", dialect="postgres").sql() 1162 'DELETE FROM tbl RETURNING *' 1163 1164 Args: 1165 expression: the SQL code strings to parse. 1166 If an `Expression` instance is passed, it will be used as-is. 1167 dialect: the dialect used to parse the input expressions. 1168 copy: if `False`, modify this expression instance in-place. 1169 opts: other options to use to parse the input expressions. 1170 1171 Returns: 1172 Delete: the modified expression. 1173 """ 1174 return _apply_builder( 1175 expression=expression, 1176 instance=self, 1177 arg="returning", 1178 prefix="RETURNING", 1179 dialect=dialect, 1180 copy=copy, 1181 into=Returning, 1182 **opts, 1183 ) 1184 1185 1186class Drop(Expression): 1187 arg_types = { 1188 "this": False, 1189 "kind": False, 1190 "exists": False, 1191 "temporary": False, 1192 "materialized": False, 1193 "cascade": False, 1194 "constraints": False, 1195 } 1196 1197 1198class Filter(Expression): 1199 arg_types = {"this": True, "expression": True} 1200 1201 1202class Check(Expression): 1203 pass 1204 1205 1206class Directory(Expression): 1207 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1208 arg_types = {"this": True, "local": False, "row_format": False} 1209 1210 1211class ForeignKey(Expression): 1212 arg_types = { 1213 "expressions": True, 1214 "reference": False, 1215 "delete": False, 1216 "update": False, 1217 } 1218 1219 1220class PrimaryKey(Expression): 1221 arg_types = {"expressions": True, "options": False} 1222 1223 1224class Unique(Expression): 1225 arg_types = {"expressions": True} 1226 1227 1228# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1229# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1230class Into(Expression): 1231 arg_types = {"this": True, "temporary": False, "unlogged": False} 1232 1233 1234class From(Expression): 1235 arg_types = {"expressions": True} 1236 1237 1238class Having(Expression): 1239 pass 1240 1241 1242class Hint(Expression): 1243 arg_types = {"expressions": True} 1244 1245 1246class JoinHint(Expression): 1247 arg_types = {"this": True, "expressions": True} 1248 1249 1250class Identifier(Expression): 1251 arg_types = {"this": True, "quoted": False} 1252 1253 @property 1254 def quoted(self): 1255 return bool(self.args.get("quoted")) 1256 1257 @property 1258 def hashable_args(self) -> t.Any: 1259 if self.quoted and any(char.isupper() for char in self.this): 1260 return (self.this, self.quoted) 1261 return self.this.lower() 1262 1263 @property 1264 def output_name(self): 1265 return self.name 1266 1267 1268class Index(Expression): 1269 arg_types = { 1270 "this": False, 1271 "table": False, 1272 "where": False, 1273 "columns": False, 1274 "unique": False, 1275 "primary": False, 1276 "amp": False, # teradata 1277 } 1278 1279 1280class Insert(Expression): 1281 arg_types = { 1282 "with": False, 1283 "this": True, 1284 "expression": False, 1285 "returning": False, 1286 "overwrite": False, 1287 "exists": False, 1288 "partition": False, 1289 "alternative": False, 1290 } 1291 1292 1293class Returning(Expression): 1294 arg_types = {"expressions": True} 1295 1296 1297# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1298class Introducer(Expression): 1299 arg_types = {"this": True, "expression": True} 1300 1301 1302# national char, like n'utf8' 1303class National(Expression): 1304 pass 1305 1306 1307class LoadData(Expression): 1308 arg_types = { 1309 "this": True, 1310 "local": False, 1311 "overwrite": False, 1312 "inpath": True, 1313 "partition": False, 1314 "input_format": False, 1315 "serde": False, 1316 } 1317 1318 1319class Partition(Expression): 1320 arg_types = {"expressions": True} 1321 1322 1323class Fetch(Expression): 1324 arg_types = {"direction": False, "count": False} 1325 1326 1327class Group(Expression): 1328 arg_types = { 1329 "expressions": False, 1330 "grouping_sets": False, 1331 "cube": False, 1332 "rollup": False, 1333 } 1334 1335 1336class Lambda(Expression): 1337 arg_types = {"this": True, "expressions": True} 1338 1339 1340class Limit(Expression): 1341 arg_types = {"this": False, "expression": True} 1342 1343 1344class Literal(Condition): 1345 arg_types = {"this": True, "is_string": True} 1346 1347 @property 1348 def hashable_args(self) -> t.Any: 1349 return (self.this, self.args.get("is_string")) 1350 1351 @classmethod 1352 def number(cls, number) -> Literal: 1353 return cls(this=str(number), is_string=False) 1354 1355 @classmethod 1356 def string(cls, string) -> Literal: 1357 return cls(this=str(string), is_string=True) 1358 1359 @property 1360 def output_name(self): 1361 return self.name 1362 1363 1364class Join(Expression): 1365 arg_types = { 1366 "this": True, 1367 "on": False, 1368 "side": False, 1369 "kind": False, 1370 "using": False, 1371 "natural": False, 1372 } 1373 1374 @property 1375 def kind(self): 1376 return self.text("kind").upper() 1377 1378 @property 1379 def side(self): 1380 return self.text("side").upper() 1381 1382 @property 1383 def alias_or_name(self): 1384 return self.this.alias_or_name 1385 1386 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1387 """ 1388 Append to or set the ON expressions. 1389 1390 Example: 1391 >>> import sqlglot 1392 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1393 'JOIN x ON y = 1' 1394 1395 Args: 1396 *expressions (str | Expression): the SQL code strings to parse. 1397 If an `Expression` instance is passed, it will be used as-is. 1398 Multiple expressions are combined with an AND operator. 1399 append (bool): if `True`, AND the new expressions to any existing expression. 1400 Otherwise, this resets the expression. 1401 dialect (str): the dialect used to parse the input expressions. 1402 copy (bool): if `False`, modify this expression instance in-place. 1403 opts (kwargs): other options to use to parse the input expressions. 1404 1405 Returns: 1406 Join: the modified join expression. 1407 """ 1408 join = _apply_conjunction_builder( 1409 *expressions, 1410 instance=self, 1411 arg="on", 1412 append=append, 1413 dialect=dialect, 1414 copy=copy, 1415 **opts, 1416 ) 1417 1418 if join.kind == "CROSS": 1419 join.set("kind", None) 1420 1421 return join 1422 1423 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1424 """ 1425 Append to or set the USING expressions. 1426 1427 Example: 1428 >>> import sqlglot 1429 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1430 'JOIN x USING (foo, bla)' 1431 1432 Args: 1433 *expressions (str | Expression): the SQL code strings to parse. 1434 If an `Expression` instance is passed, it will be used as-is. 1435 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1436 Otherwise, this resets the expression. 1437 dialect (str): the dialect used to parse the input expressions. 1438 copy (bool): if `False`, modify this expression instance in-place. 1439 opts (kwargs): other options to use to parse the input expressions. 1440 1441 Returns: 1442 Join: the modified join expression. 1443 """ 1444 join = _apply_list_builder( 1445 *expressions, 1446 instance=self, 1447 arg="using", 1448 append=append, 1449 dialect=dialect, 1450 copy=copy, 1451 **opts, 1452 ) 1453 1454 if join.kind == "CROSS": 1455 join.set("kind", None) 1456 1457 return join 1458 1459 1460class Lateral(UDTF): 1461 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1462 1463 1464class MatchRecognize(Expression): 1465 arg_types = { 1466 "partition_by": False, 1467 "order": False, 1468 "measures": False, 1469 "rows": False, 1470 "after": False, 1471 "pattern": False, 1472 "define": False, 1473 } 1474 1475 1476# Clickhouse FROM FINAL modifier 1477# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1478class Final(Expression): 1479 pass 1480 1481 1482class Offset(Expression): 1483 arg_types = {"this": False, "expression": True} 1484 1485 1486class Order(Expression): 1487 arg_types = {"this": False, "expressions": True} 1488 1489 1490# hive specific sorts 1491# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1492class Cluster(Order): 1493 pass 1494 1495 1496class Distribute(Order): 1497 pass 1498 1499 1500class Sort(Order): 1501 pass 1502 1503 1504class Ordered(Expression): 1505 arg_types = {"this": True, "desc": True, "nulls_first": True} 1506 1507 1508class Property(Expression): 1509 arg_types = {"this": True, "value": True} 1510 1511 1512class AfterJournalProperty(Property): 1513 arg_types = {"no": True, "dual": False, "local": False} 1514 1515 1516class AlgorithmProperty(Property): 1517 arg_types = {"this": True} 1518 1519 1520class AutoIncrementProperty(Property): 1521 arg_types = {"this": True} 1522 1523 1524class BlockCompressionProperty(Property): 1525 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1526 1527 1528class CharacterSetProperty(Property): 1529 arg_types = {"this": True, "default": True} 1530 1531 1532class ChecksumProperty(Property): 1533 arg_types = {"on": False, "default": False} 1534 1535 1536class CollateProperty(Property): 1537 arg_types = {"this": True} 1538 1539 1540class DataBlocksizeProperty(Property): 1541 arg_types = {"size": False, "units": False, "min": False, "default": False} 1542 1543 1544class DefinerProperty(Property): 1545 arg_types = {"this": True} 1546 1547 1548class DistKeyProperty(Property): 1549 arg_types = {"this": True} 1550 1551 1552class DistStyleProperty(Property): 1553 arg_types = {"this": True} 1554 1555 1556class EngineProperty(Property): 1557 arg_types = {"this": True} 1558 1559 1560class ExecuteAsProperty(Property): 1561 arg_types = {"this": True} 1562 1563 1564class ExternalProperty(Property): 1565 arg_types = {"this": False} 1566 1567 1568class FallbackProperty(Property): 1569 arg_types = {"no": True, "protection": False} 1570 1571 1572class FileFormatProperty(Property): 1573 arg_types = {"this": True} 1574 1575 1576class FreespaceProperty(Property): 1577 arg_types = {"this": True, "percent": False} 1578 1579 1580class IsolatedLoadingProperty(Property): 1581 arg_types = { 1582 "no": True, 1583 "concurrent": True, 1584 "for_all": True, 1585 "for_insert": True, 1586 "for_none": True, 1587 } 1588 1589 1590class JournalProperty(Property): 1591 arg_types = {"no": True, "dual": False, "before": False} 1592 1593 1594class LanguageProperty(Property): 1595 arg_types = {"this": True} 1596 1597 1598class LikeProperty(Property): 1599 arg_types = {"this": True, "expressions": False} 1600 1601 1602class LocationProperty(Property): 1603 arg_types = {"this": True} 1604 1605 1606class LockingProperty(Property): 1607 arg_types = { 1608 "this": False, 1609 "kind": True, 1610 "for_or_in": True, 1611 "lock_type": True, 1612 "override": False, 1613 } 1614 1615 1616class LogProperty(Property): 1617 arg_types = {"no": True} 1618 1619 1620class MaterializedProperty(Property): 1621 arg_types = {"this": False} 1622 1623 1624class MergeBlockRatioProperty(Property): 1625 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1626 1627 1628class NoPrimaryIndexProperty(Property): 1629 arg_types = {"this": False} 1630 1631 1632class OnCommitProperty(Property): 1633 arg_type = {"this": False} 1634 1635 1636class PartitionedByProperty(Property): 1637 arg_types = {"this": True} 1638 1639 1640class ReturnsProperty(Property): 1641 arg_types = {"this": True, "is_table": False, "table": False} 1642 1643 1644class RowFormatDelimitedProperty(Property): 1645 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1646 arg_types = { 1647 "fields": False, 1648 "escaped": False, 1649 "collection_items": False, 1650 "map_keys": False, 1651 "lines": False, 1652 "null": False, 1653 "serde": False, 1654 } 1655 1656 1657class RowFormatSerdeProperty(Property): 1658 arg_types = {"this": True} 1659 1660 1661class SchemaCommentProperty(Property): 1662 arg_types = {"this": True} 1663 1664 1665class SerdeProperties(Property): 1666 arg_types = {"expressions": True} 1667 1668 1669class SetProperty(Property): 1670 arg_types = {"multi": True} 1671 1672 1673class SortKeyProperty(Property): 1674 arg_types = {"this": True, "compound": False} 1675 1676 1677class SqlSecurityProperty(Property): 1678 arg_types = {"definer": True} 1679 1680 1681class TableFormatProperty(Property): 1682 arg_types = {"this": True} 1683 1684 1685class TemporaryProperty(Property): 1686 arg_types = {"global_": True} 1687 1688 1689class TransientProperty(Property): 1690 arg_types = {"this": False} 1691 1692 1693class VolatilityProperty(Property): 1694 arg_types = {"this": True} 1695 1696 1697class WithDataProperty(Property): 1698 arg_types = {"no": True, "statistics": False} 1699 1700 1701class WithJournalTableProperty(Property): 1702 arg_types = {"this": True} 1703 1704 1705class Properties(Expression): 1706 arg_types = {"expressions": True} 1707 1708 NAME_TO_PROPERTY = { 1709 "ALGORITHM": AlgorithmProperty, 1710 "AUTO_INCREMENT": AutoIncrementProperty, 1711 "CHARACTER SET": CharacterSetProperty, 1712 "COLLATE": CollateProperty, 1713 "COMMENT": SchemaCommentProperty, 1714 "DEFINER": DefinerProperty, 1715 "DISTKEY": DistKeyProperty, 1716 "DISTSTYLE": DistStyleProperty, 1717 "ENGINE": EngineProperty, 1718 "EXECUTE AS": ExecuteAsProperty, 1719 "FORMAT": FileFormatProperty, 1720 "LANGUAGE": LanguageProperty, 1721 "LOCATION": LocationProperty, 1722 "PARTITIONED_BY": PartitionedByProperty, 1723 "RETURNS": ReturnsProperty, 1724 "SORTKEY": SortKeyProperty, 1725 "TABLE_FORMAT": TableFormatProperty, 1726 } 1727 1728 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1729 1730 # CREATE property locations 1731 # Form: schema specified 1732 # create [POST_CREATE] 1733 # table a [POST_NAME] 1734 # (b int) [POST_SCHEMA] 1735 # with ([POST_WITH]) 1736 # index (b) [POST_INDEX] 1737 # 1738 # Form: alias selection 1739 # create [POST_CREATE] 1740 # table a [POST_NAME] 1741 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1742 # index (c) [POST_INDEX] 1743 class Location(AutoName): 1744 POST_CREATE = auto() 1745 POST_NAME = auto() 1746 POST_SCHEMA = auto() 1747 POST_WITH = auto() 1748 POST_ALIAS = auto() 1749 POST_EXPRESSION = auto() 1750 POST_INDEX = auto() 1751 UNSUPPORTED = auto() 1752 1753 @classmethod 1754 def from_dict(cls, properties_dict) -> Properties: 1755 expressions = [] 1756 for key, value in properties_dict.items(): 1757 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1758 if property_cls: 1759 expressions.append(property_cls(this=convert(value))) 1760 else: 1761 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1762 1763 return cls(expressions=expressions) 1764 1765 1766class Qualify(Expression): 1767 pass 1768 1769 1770# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 1771class Return(Expression): 1772 pass 1773 1774 1775class Reference(Expression): 1776 arg_types = {"this": True, "expressions": False, "options": False} 1777 1778 1779class Tuple(Expression): 1780 arg_types = {"expressions": False} 1781 1782 1783class Subqueryable(Unionable): 1784 def subquery(self, alias=None, copy=True) -> Subquery: 1785 """ 1786 Convert this expression to an aliased expression that can be used as a Subquery. 1787 1788 Example: 1789 >>> subquery = Select().select("x").from_("tbl").subquery() 1790 >>> Select().select("x").from_(subquery).sql() 1791 'SELECT x FROM (SELECT x FROM tbl)' 1792 1793 Args: 1794 alias (str | Identifier): an optional alias for the subquery 1795 copy (bool): if `False`, modify this expression instance in-place. 1796 1797 Returns: 1798 Alias: the subquery 1799 """ 1800 instance = _maybe_copy(self, copy) 1801 return Subquery( 1802 this=instance, 1803 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1804 ) 1805 1806 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1807 raise NotImplementedError 1808 1809 @property 1810 def ctes(self): 1811 with_ = self.args.get("with") 1812 if not with_: 1813 return [] 1814 return with_.expressions 1815 1816 @property 1817 def selects(self): 1818 raise NotImplementedError("Subqueryable objects must implement `selects`") 1819 1820 @property 1821 def named_selects(self): 1822 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1823 1824 def with_( 1825 self, 1826 alias, 1827 as_, 1828 recursive=None, 1829 append=True, 1830 dialect=None, 1831 copy=True, 1832 **opts, 1833 ): 1834 """ 1835 Append to or set the common table expressions. 1836 1837 Example: 1838 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1839 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1840 1841 Args: 1842 alias (str | Expression): the SQL code string to parse as the table name. 1843 If an `Expression` instance is passed, this is used as-is. 1844 as_ (str | Expression): the SQL code string to parse as the table expression. 1845 If an `Expression` instance is passed, it will be used as-is. 1846 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1847 append (bool): if `True`, add to any existing expressions. 1848 Otherwise, this resets the expressions. 1849 dialect (str): the dialect used to parse the input expression. 1850 copy (bool): if `False`, modify this expression instance in-place. 1851 opts (kwargs): other options to use to parse the input expressions. 1852 1853 Returns: 1854 Select: the modified expression. 1855 """ 1856 alias_expression = maybe_parse( 1857 alias, 1858 dialect=dialect, 1859 into=TableAlias, 1860 **opts, 1861 ) 1862 as_expression = maybe_parse( 1863 as_, 1864 dialect=dialect, 1865 **opts, 1866 ) 1867 cte = CTE( 1868 this=as_expression, 1869 alias=alias_expression, 1870 ) 1871 return _apply_child_list_builder( 1872 cte, 1873 instance=self, 1874 arg="with", 1875 append=append, 1876 copy=copy, 1877 into=With, 1878 properties={"recursive": recursive or False}, 1879 ) 1880 1881 1882QUERY_MODIFIERS = { 1883 "match": False, 1884 "laterals": False, 1885 "joins": False, 1886 "pivots": False, 1887 "where": False, 1888 "group": False, 1889 "having": False, 1890 "qualify": False, 1891 "windows": False, 1892 "distribute": False, 1893 "sort": False, 1894 "cluster": False, 1895 "order": False, 1896 "limit": False, 1897 "offset": False, 1898 "lock": False, 1899 "sample": False, 1900} 1901 1902 1903class Table(Expression): 1904 arg_types = { 1905 "this": True, 1906 "alias": False, 1907 "db": False, 1908 "catalog": False, 1909 "laterals": False, 1910 "joins": False, 1911 "pivots": False, 1912 "hints": False, 1913 "system_time": False, 1914 } 1915 1916 @property 1917 def db(self) -> str: 1918 return self.text("db") 1919 1920 @property 1921 def catalog(self) -> str: 1922 return self.text("catalog") 1923 1924 1925# See the TSQL "Querying data in a system-versioned temporal table" page 1926class SystemTime(Expression): 1927 arg_types = { 1928 "this": False, 1929 "expression": False, 1930 "kind": True, 1931 } 1932 1933 1934class Union(Subqueryable): 1935 arg_types = { 1936 "with": False, 1937 "this": True, 1938 "expression": True, 1939 "distinct": False, 1940 **QUERY_MODIFIERS, 1941 } 1942 1943 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1944 """ 1945 Set the LIMIT expression. 1946 1947 Example: 1948 >>> select("1").union(select("1")).limit(1).sql() 1949 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1950 1951 Args: 1952 expression (str | int | Expression): the SQL code string to parse. 1953 This can also be an integer. 1954 If a `Limit` instance is passed, this is used as-is. 1955 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1956 dialect (str): the dialect used to parse the input expression. 1957 copy (bool): if `False`, modify this expression instance in-place. 1958 opts (kwargs): other options to use to parse the input expressions. 1959 1960 Returns: 1961 Select: The limited subqueryable. 1962 """ 1963 return ( 1964 select("*") 1965 .from_(self.subquery(alias="_l_0", copy=copy)) 1966 .limit(expression, dialect=dialect, copy=False, **opts) 1967 ) 1968 1969 def select( 1970 self, 1971 *expressions: ExpOrStr, 1972 append: bool = True, 1973 dialect: DialectType = None, 1974 copy: bool = True, 1975 **opts, 1976 ) -> Union: 1977 """Append to or set the SELECT of the union recursively. 1978 1979 Example: 1980 >>> from sqlglot import parse_one 1981 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1982 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1983 1984 Args: 1985 *expressions: the SQL code strings to parse. 1986 If an `Expression` instance is passed, it will be used as-is. 1987 append: if `True`, add to any existing expressions. 1988 Otherwise, this resets the expressions. 1989 dialect: the dialect used to parse the input expressions. 1990 copy: if `False`, modify this expression instance in-place. 1991 opts: other options to use to parse the input expressions. 1992 1993 Returns: 1994 Union: the modified expression. 1995 """ 1996 this = self.copy() if copy else self 1997 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1998 this.expression.unnest().select( 1999 *expressions, append=append, dialect=dialect, copy=False, **opts 2000 ) 2001 return this 2002 2003 @property 2004 def named_selects(self): 2005 return self.this.unnest().named_selects 2006 2007 @property 2008 def is_star(self) -> bool: 2009 return self.this.is_star or self.expression.is_star 2010 2011 @property 2012 def selects(self): 2013 return self.this.unnest().selects 2014 2015 @property 2016 def left(self): 2017 return self.this 2018 2019 @property 2020 def right(self): 2021 return self.expression 2022 2023 2024class Except(Union): 2025 pass 2026 2027 2028class Intersect(Union): 2029 pass 2030 2031 2032class Unnest(UDTF): 2033 arg_types = { 2034 "expressions": True, 2035 "ordinality": False, 2036 "alias": False, 2037 "offset": False, 2038 } 2039 2040 2041class Update(Expression): 2042 arg_types = { 2043 "with": False, 2044 "this": False, 2045 "expressions": True, 2046 "from": False, 2047 "where": False, 2048 "returning": False, 2049 } 2050 2051 2052class Values(UDTF): 2053 arg_types = { 2054 "expressions": True, 2055 "ordinality": False, 2056 "alias": False, 2057 } 2058 2059 2060class Var(Expression): 2061 pass 2062 2063 2064class Schema(Expression): 2065 arg_types = {"this": False, "expressions": False} 2066 2067 2068# Used to represent the FOR UPDATE and FOR SHARE locking read types. 2069# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html 2070class Lock(Expression): 2071 arg_types = {"update": True} 2072 2073 2074class Select(Subqueryable): 2075 arg_types = { 2076 "with": False, 2077 "kind": False, 2078 "expressions": False, 2079 "hint": False, 2080 "distinct": False, 2081 "into": False, 2082 "from": False, 2083 **QUERY_MODIFIERS, 2084 } 2085 2086 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2087 """ 2088 Set the FROM expression. 2089 2090 Example: 2091 >>> Select().from_("tbl").select("x").sql() 2092 'SELECT x FROM tbl' 2093 2094 Args: 2095 *expressions (str | Expression): the SQL code strings to parse. 2096 If a `From` instance is passed, this is used as-is. 2097 If another `Expression` instance is passed, it will be wrapped in a `From`. 2098 append (bool): if `True`, add to any existing expressions. 2099 Otherwise, this flattens all the `From` expression into a single expression. 2100 dialect (str): the dialect used to parse the input expression. 2101 copy (bool): if `False`, modify this expression instance in-place. 2102 opts (kwargs): other options to use to parse the input expressions. 2103 2104 Returns: 2105 Select: the modified expression. 2106 """ 2107 return _apply_child_list_builder( 2108 *expressions, 2109 instance=self, 2110 arg="from", 2111 append=append, 2112 copy=copy, 2113 prefix="FROM", 2114 into=From, 2115 dialect=dialect, 2116 **opts, 2117 ) 2118 2119 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2120 """ 2121 Set the GROUP BY expression. 2122 2123 Example: 2124 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2125 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2126 2127 Args: 2128 *expressions (str | Expression): the SQL code strings to parse. 2129 If a `Group` instance is passed, this is used as-is. 2130 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2131 If nothing is passed in then a group by is not applied to the expression 2132 append (bool): if `True`, add to any existing expressions. 2133 Otherwise, this flattens all the `Group` expression into a single expression. 2134 dialect (str): the dialect used to parse the input expression. 2135 copy (bool): if `False`, modify this expression instance in-place. 2136 opts (kwargs): other options to use to parse the input expressions. 2137 2138 Returns: 2139 Select: the modified expression. 2140 """ 2141 if not expressions: 2142 return self if not copy else self.copy() 2143 return _apply_child_list_builder( 2144 *expressions, 2145 instance=self, 2146 arg="group", 2147 append=append, 2148 copy=copy, 2149 prefix="GROUP BY", 2150 into=Group, 2151 dialect=dialect, 2152 **opts, 2153 ) 2154 2155 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2156 """ 2157 Set the ORDER BY expression. 2158 2159 Example: 2160 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2161 'SELECT x FROM tbl ORDER BY x DESC' 2162 2163 Args: 2164 *expressions (str | Expression): the SQL code strings to parse. 2165 If a `Group` instance is passed, this is used as-is. 2166 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2167 append (bool): if `True`, add to any existing expressions. 2168 Otherwise, this flattens all the `Order` expression into a single expression. 2169 dialect (str): the dialect used to parse the input expression. 2170 copy (bool): if `False`, modify this expression instance in-place. 2171 opts (kwargs): other options to use to parse the input expressions. 2172 2173 Returns: 2174 Select: the modified expression. 2175 """ 2176 return _apply_child_list_builder( 2177 *expressions, 2178 instance=self, 2179 arg="order", 2180 append=append, 2181 copy=copy, 2182 prefix="ORDER BY", 2183 into=Order, 2184 dialect=dialect, 2185 **opts, 2186 ) 2187 2188 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2189 """ 2190 Set the SORT BY expression. 2191 2192 Example: 2193 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2194 'SELECT x FROM tbl SORT BY x DESC' 2195 2196 Args: 2197 *expressions (str | Expression): the SQL code strings to parse. 2198 If a `Group` instance is passed, this is used as-is. 2199 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2200 append (bool): if `True`, add to any existing expressions. 2201 Otherwise, this flattens all the `Order` expression into a single expression. 2202 dialect (str): the dialect used to parse the input expression. 2203 copy (bool): if `False`, modify this expression instance in-place. 2204 opts (kwargs): other options to use to parse the input expressions. 2205 2206 Returns: 2207 Select: the modified expression. 2208 """ 2209 return _apply_child_list_builder( 2210 *expressions, 2211 instance=self, 2212 arg="sort", 2213 append=append, 2214 copy=copy, 2215 prefix="SORT BY", 2216 into=Sort, 2217 dialect=dialect, 2218 **opts, 2219 ) 2220 2221 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2222 """ 2223 Set the CLUSTER BY expression. 2224 2225 Example: 2226 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2227 'SELECT x FROM tbl CLUSTER BY x DESC' 2228 2229 Args: 2230 *expressions (str | Expression): the SQL code strings to parse. 2231 If a `Group` instance is passed, this is used as-is. 2232 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2233 append (bool): if `True`, add to any existing expressions. 2234 Otherwise, this flattens all the `Order` expression into a single expression. 2235 dialect (str): the dialect used to parse the input expression. 2236 copy (bool): if `False`, modify this expression instance in-place. 2237 opts (kwargs): other options to use to parse the input expressions. 2238 2239 Returns: 2240 Select: the modified expression. 2241 """ 2242 return _apply_child_list_builder( 2243 *expressions, 2244 instance=self, 2245 arg="cluster", 2246 append=append, 2247 copy=copy, 2248 prefix="CLUSTER BY", 2249 into=Cluster, 2250 dialect=dialect, 2251 **opts, 2252 ) 2253 2254 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2255 """ 2256 Set the LIMIT expression. 2257 2258 Example: 2259 >>> Select().from_("tbl").select("x").limit(10).sql() 2260 'SELECT x FROM tbl LIMIT 10' 2261 2262 Args: 2263 expression (str | int | Expression): the SQL code string to parse. 2264 This can also be an integer. 2265 If a `Limit` instance is passed, this is used as-is. 2266 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2267 dialect (str): the dialect used to parse the input expression. 2268 copy (bool): if `False`, modify this expression instance in-place. 2269 opts (kwargs): other options to use to parse the input expressions. 2270 2271 Returns: 2272 Select: the modified expression. 2273 """ 2274 return _apply_builder( 2275 expression=expression, 2276 instance=self, 2277 arg="limit", 2278 into=Limit, 2279 prefix="LIMIT", 2280 dialect=dialect, 2281 copy=copy, 2282 **opts, 2283 ) 2284 2285 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2286 """ 2287 Set the OFFSET expression. 2288 2289 Example: 2290 >>> Select().from_("tbl").select("x").offset(10).sql() 2291 'SELECT x FROM tbl OFFSET 10' 2292 2293 Args: 2294 expression (str | int | Expression): the SQL code string to parse. 2295 This can also be an integer. 2296 If a `Offset` instance is passed, this is used as-is. 2297 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2298 dialect (str): the dialect used to parse the input expression. 2299 copy (bool): if `False`, modify this expression instance in-place. 2300 opts (kwargs): other options to use to parse the input expressions. 2301 2302 Returns: 2303 Select: the modified expression. 2304 """ 2305 return _apply_builder( 2306 expression=expression, 2307 instance=self, 2308 arg="offset", 2309 into=Offset, 2310 prefix="OFFSET", 2311 dialect=dialect, 2312 copy=copy, 2313 **opts, 2314 ) 2315 2316 def select( 2317 self, 2318 *expressions: ExpOrStr, 2319 append: bool = True, 2320 dialect: DialectType = None, 2321 copy: bool = True, 2322 **opts, 2323 ) -> Select: 2324 """ 2325 Append to or set the SELECT expressions. 2326 2327 Example: 2328 >>> Select().select("x", "y").sql() 2329 'SELECT x, y' 2330 2331 Args: 2332 *expressions: the SQL code strings to parse. 2333 If an `Expression` instance is passed, it will be used as-is. 2334 append: if `True`, add to any existing expressions. 2335 Otherwise, this resets the expressions. 2336 dialect: the dialect used to parse the input expressions. 2337 copy: if `False`, modify this expression instance in-place. 2338 opts: other options to use to parse the input expressions. 2339 2340 Returns: 2341 Select: the modified expression. 2342 """ 2343 return _apply_list_builder( 2344 *expressions, 2345 instance=self, 2346 arg="expressions", 2347 append=append, 2348 dialect=dialect, 2349 copy=copy, 2350 **opts, 2351 ) 2352 2353 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2354 """ 2355 Append to or set the LATERAL expressions. 2356 2357 Example: 2358 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2359 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2360 2361 Args: 2362 *expressions (str | Expression): the SQL code strings to parse. 2363 If an `Expression` instance is passed, it will be used as-is. 2364 append (bool): if `True`, add to any existing expressions. 2365 Otherwise, this resets the expressions. 2366 dialect (str): the dialect used to parse the input expressions. 2367 copy (bool): if `False`, modify this expression instance in-place. 2368 opts (kwargs): other options to use to parse the input expressions. 2369 2370 Returns: 2371 Select: the modified expression. 2372 """ 2373 return _apply_list_builder( 2374 *expressions, 2375 instance=self, 2376 arg="laterals", 2377 append=append, 2378 into=Lateral, 2379 prefix="LATERAL VIEW", 2380 dialect=dialect, 2381 copy=copy, 2382 **opts, 2383 ) 2384 2385 def join( 2386 self, 2387 expression, 2388 on=None, 2389 using=None, 2390 append=True, 2391 join_type=None, 2392 join_alias=None, 2393 dialect=None, 2394 copy=True, 2395 **opts, 2396 ) -> Select: 2397 """ 2398 Append to or set the JOIN expressions. 2399 2400 Example: 2401 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2402 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2403 2404 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2405 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2406 2407 Use `join_type` to change the type of join: 2408 2409 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2410 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2411 2412 Args: 2413 expression (str | Expression): the SQL code string to parse. 2414 If an `Expression` instance is passed, it will be used as-is. 2415 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2416 If an `Expression` instance is passed, it will be used as-is. 2417 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2418 If an `Expression` instance is passed, it will be used as-is. 2419 append (bool): if `True`, add to any existing expressions. 2420 Otherwise, this resets the expressions. 2421 join_type (str): If set, alter the parsed join type 2422 dialect (str): the dialect used to parse the input expressions. 2423 copy (bool): if `False`, modify this expression instance in-place. 2424 opts (kwargs): other options to use to parse the input expressions. 2425 2426 Returns: 2427 Select: the modified expression. 2428 """ 2429 parse_args = {"dialect": dialect, **opts} 2430 2431 try: 2432 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2433 except ParseError: 2434 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2435 2436 join = expression if isinstance(expression, Join) else Join(this=expression) 2437 2438 if isinstance(join.this, Select): 2439 join.this.replace(join.this.subquery()) 2440 2441 if join_type: 2442 natural: t.Optional[Token] 2443 side: t.Optional[Token] 2444 kind: t.Optional[Token] 2445 2446 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2447 2448 if natural: 2449 join.set("natural", True) 2450 if side: 2451 join.set("side", side.text) 2452 if kind: 2453 join.set("kind", kind.text) 2454 2455 if on: 2456 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2457 join.set("on", on) 2458 2459 if using: 2460 join = _apply_list_builder( 2461 *ensure_collection(using), 2462 instance=join, 2463 arg="using", 2464 append=append, 2465 copy=copy, 2466 **opts, 2467 ) 2468 2469 if join_alias: 2470 join.set("this", alias_(join.this, join_alias, table=True)) 2471 return _apply_list_builder( 2472 join, 2473 instance=self, 2474 arg="joins", 2475 append=append, 2476 copy=copy, 2477 **opts, 2478 ) 2479 2480 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2481 """ 2482 Append to or set the WHERE expressions. 2483 2484 Example: 2485 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2486 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2487 2488 Args: 2489 *expressions (str | Expression): the SQL code strings to parse. 2490 If an `Expression` instance is passed, it will be used as-is. 2491 Multiple expressions are combined with an AND operator. 2492 append (bool): if `True`, AND the new expressions to any existing expression. 2493 Otherwise, this resets the expression. 2494 dialect (str): the dialect used to parse the input expressions. 2495 copy (bool): if `False`, modify this expression instance in-place. 2496 opts (kwargs): other options to use to parse the input expressions. 2497 2498 Returns: 2499 Select: the modified expression. 2500 """ 2501 return _apply_conjunction_builder( 2502 *expressions, 2503 instance=self, 2504 arg="where", 2505 append=append, 2506 into=Where, 2507 dialect=dialect, 2508 copy=copy, 2509 **opts, 2510 ) 2511 2512 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2513 """ 2514 Append to or set the HAVING expressions. 2515 2516 Example: 2517 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2518 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2519 2520 Args: 2521 *expressions (str | Expression): the SQL code strings to parse. 2522 If an `Expression` instance is passed, it will be used as-is. 2523 Multiple expressions are combined with an AND operator. 2524 append (bool): if `True`, AND the new expressions to any existing expression. 2525 Otherwise, this resets the expression. 2526 dialect (str): the dialect used to parse the input expressions. 2527 copy (bool): if `False`, modify this expression instance in-place. 2528 opts (kwargs): other options to use to parse the input expressions. 2529 2530 Returns: 2531 Select: the modified expression. 2532 """ 2533 return _apply_conjunction_builder( 2534 *expressions, 2535 instance=self, 2536 arg="having", 2537 append=append, 2538 into=Having, 2539 dialect=dialect, 2540 copy=copy, 2541 **opts, 2542 ) 2543 2544 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2545 return _apply_list_builder( 2546 *expressions, 2547 instance=self, 2548 arg="windows", 2549 append=append, 2550 into=Window, 2551 dialect=dialect, 2552 copy=copy, 2553 **opts, 2554 ) 2555 2556 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2557 return _apply_conjunction_builder( 2558 *expressions, 2559 instance=self, 2560 arg="qualify", 2561 append=append, 2562 into=Qualify, 2563 dialect=dialect, 2564 copy=copy, 2565 **opts, 2566 ) 2567 2568 def distinct(self, distinct=True, copy=True) -> Select: 2569 """ 2570 Set the OFFSET expression. 2571 2572 Example: 2573 >>> Select().from_("tbl").select("x").distinct().sql() 2574 'SELECT DISTINCT x FROM tbl' 2575 2576 Args: 2577 distinct (bool): whether the Select should be distinct 2578 copy (bool): if `False`, modify this expression instance in-place. 2579 2580 Returns: 2581 Select: the modified expression. 2582 """ 2583 instance = _maybe_copy(self, copy) 2584 instance.set("distinct", Distinct() if distinct else None) 2585 return instance 2586 2587 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2588 """ 2589 Convert this expression to a CREATE TABLE AS statement. 2590 2591 Example: 2592 >>> Select().select("*").from_("tbl").ctas("x").sql() 2593 'CREATE TABLE x AS SELECT * FROM tbl' 2594 2595 Args: 2596 table (str | Expression): the SQL code string to parse as the table name. 2597 If another `Expression` instance is passed, it will be used as-is. 2598 properties (dict): an optional mapping of table properties 2599 dialect (str): the dialect used to parse the input table. 2600 copy (bool): if `False`, modify this expression instance in-place. 2601 opts (kwargs): other options to use to parse the input table. 2602 2603 Returns: 2604 Create: the CREATE TABLE AS expression 2605 """ 2606 instance = _maybe_copy(self, copy) 2607 table_expression = maybe_parse( 2608 table, 2609 into=Table, 2610 dialect=dialect, 2611 **opts, 2612 ) 2613 properties_expression = None 2614 if properties: 2615 properties_expression = Properties.from_dict(properties) 2616 2617 return Create( 2618 this=table_expression, 2619 kind="table", 2620 expression=instance, 2621 properties=properties_expression, 2622 ) 2623 2624 def lock(self, update: bool = True, copy: bool = True) -> Select: 2625 """ 2626 Set the locking read mode for this expression. 2627 2628 Examples: 2629 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2630 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2631 2632 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2633 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2634 2635 Args: 2636 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2637 copy: if `False`, modify this expression instance in-place. 2638 2639 Returns: 2640 The modified expression. 2641 """ 2642 2643 inst = _maybe_copy(self, copy) 2644 inst.set("lock", Lock(update=update)) 2645 2646 return inst 2647 2648 @property 2649 def named_selects(self) -> t.List[str]: 2650 return [e.output_name for e in self.expressions if e.alias_or_name] 2651 2652 @property 2653 def is_star(self) -> bool: 2654 return any(expression.is_star for expression in self.expressions) 2655 2656 @property 2657 def selects(self) -> t.List[Expression]: 2658 return self.expressions 2659 2660 2661class Subquery(DerivedTable, Unionable): 2662 arg_types = { 2663 "this": True, 2664 "alias": False, 2665 "with": False, 2666 **QUERY_MODIFIERS, 2667 } 2668 2669 def unnest(self): 2670 """ 2671 Returns the first non subquery. 2672 """ 2673 expression = self 2674 while isinstance(expression, Subquery): 2675 expression = expression.this 2676 return expression 2677 2678 @property 2679 def is_star(self) -> bool: 2680 return self.this.is_star 2681 2682 @property 2683 def output_name(self): 2684 return self.alias 2685 2686 2687class TableSample(Expression): 2688 arg_types = { 2689 "this": False, 2690 "method": False, 2691 "bucket_numerator": False, 2692 "bucket_denominator": False, 2693 "bucket_field": False, 2694 "percent": False, 2695 "rows": False, 2696 "size": False, 2697 "seed": False, 2698 "kind": False, 2699 } 2700 2701 2702class Tag(Expression): 2703 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2704 2705 arg_types = { 2706 "this": False, 2707 "prefix": False, 2708 "postfix": False, 2709 } 2710 2711 2712class Pivot(Expression): 2713 arg_types = { 2714 "this": False, 2715 "alias": False, 2716 "expressions": True, 2717 "field": True, 2718 "unpivot": True, 2719 } 2720 2721 2722class Window(Expression): 2723 arg_types = { 2724 "this": True, 2725 "partition_by": False, 2726 "order": False, 2727 "spec": False, 2728 "alias": False, 2729 } 2730 2731 2732class WindowSpec(Expression): 2733 arg_types = { 2734 "kind": False, 2735 "start": False, 2736 "start_side": False, 2737 "end": False, 2738 "end_side": False, 2739 } 2740 2741 2742class Where(Expression): 2743 pass 2744 2745 2746class Star(Expression): 2747 arg_types = {"except": False, "replace": False} 2748 2749 @property 2750 def name(self) -> str: 2751 return "*" 2752 2753 @property 2754 def output_name(self): 2755 return self.name 2756 2757 2758class Parameter(Expression): 2759 arg_types = {"this": True, "wrapped": False} 2760 2761 2762class SessionParameter(Expression): 2763 arg_types = {"this": True, "kind": False} 2764 2765 2766class Placeholder(Expression): 2767 arg_types = {"this": False} 2768 2769 2770class Null(Condition): 2771 arg_types: t.Dict[str, t.Any] = {} 2772 2773 @property 2774 def name(self) -> str: 2775 return "NULL" 2776 2777 2778class Boolean(Condition): 2779 pass 2780 2781 2782class DataType(Expression): 2783 arg_types = { 2784 "this": True, 2785 "expressions": False, 2786 "nested": False, 2787 "values": False, 2788 "prefix": False, 2789 } 2790 2791 class Type(AutoName): 2792 CHAR = auto() 2793 NCHAR = auto() 2794 VARCHAR = auto() 2795 NVARCHAR = auto() 2796 TEXT = auto() 2797 MEDIUMTEXT = auto() 2798 LONGTEXT = auto() 2799 MEDIUMBLOB = auto() 2800 LONGBLOB = auto() 2801 BINARY = auto() 2802 VARBINARY = auto() 2803 INT = auto() 2804 UINT = auto() 2805 TINYINT = auto() 2806 UTINYINT = auto() 2807 SMALLINT = auto() 2808 USMALLINT = auto() 2809 BIGINT = auto() 2810 UBIGINT = auto() 2811 FLOAT = auto() 2812 DOUBLE = auto() 2813 DECIMAL = auto() 2814 BIT = auto() 2815 BOOLEAN = auto() 2816 JSON = auto() 2817 JSONB = auto() 2818 INTERVAL = auto() 2819 TIME = auto() 2820 TIMESTAMP = auto() 2821 TIMESTAMPTZ = auto() 2822 TIMESTAMPLTZ = auto() 2823 DATE = auto() 2824 DATETIME = auto() 2825 ARRAY = auto() 2826 MAP = auto() 2827 UUID = auto() 2828 GEOGRAPHY = auto() 2829 GEOMETRY = auto() 2830 STRUCT = auto() 2831 NULLABLE = auto() 2832 HLLSKETCH = auto() 2833 HSTORE = auto() 2834 SUPER = auto() 2835 SERIAL = auto() 2836 SMALLSERIAL = auto() 2837 BIGSERIAL = auto() 2838 XML = auto() 2839 UNIQUEIDENTIFIER = auto() 2840 MONEY = auto() 2841 SMALLMONEY = auto() 2842 ROWVERSION = auto() 2843 IMAGE = auto() 2844 VARIANT = auto() 2845 OBJECT = auto() 2846 INET = auto() 2847 NULL = auto() 2848 UNKNOWN = auto() # Sentinel value, useful for type annotation 2849 2850 TEXT_TYPES = { 2851 Type.CHAR, 2852 Type.NCHAR, 2853 Type.VARCHAR, 2854 Type.NVARCHAR, 2855 Type.TEXT, 2856 } 2857 2858 INTEGER_TYPES = { 2859 Type.INT, 2860 Type.TINYINT, 2861 Type.SMALLINT, 2862 Type.BIGINT, 2863 } 2864 2865 FLOAT_TYPES = { 2866 Type.FLOAT, 2867 Type.DOUBLE, 2868 } 2869 2870 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2871 2872 TEMPORAL_TYPES = { 2873 Type.TIMESTAMP, 2874 Type.TIMESTAMPTZ, 2875 Type.TIMESTAMPLTZ, 2876 Type.DATE, 2877 Type.DATETIME, 2878 } 2879 2880 @classmethod 2881 def build( 2882 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2883 ) -> DataType: 2884 from sqlglot import parse_one 2885 2886 if isinstance(dtype, str): 2887 if dtype.upper() in cls.Type.__members__: 2888 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2889 else: 2890 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2891 if data_type_exp is None: 2892 raise ValueError(f"Unparsable data type value: {dtype}") 2893 elif isinstance(dtype, DataType.Type): 2894 data_type_exp = DataType(this=dtype) 2895 elif isinstance(dtype, DataType): 2896 return dtype 2897 else: 2898 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2899 return DataType(**{**data_type_exp.args, **kwargs}) 2900 2901 def is_type(self, dtype: DataType.Type) -> bool: 2902 return self.this == dtype 2903 2904 2905# https://www.postgresql.org/docs/15/datatype-pseudo.html 2906class PseudoType(Expression): 2907 pass 2908 2909 2910class StructKwarg(Expression): 2911 arg_types = {"this": True, "expression": True} 2912 2913 2914# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 2915class SubqueryPredicate(Predicate): 2916 pass 2917 2918 2919class All(SubqueryPredicate): 2920 pass 2921 2922 2923class Any(SubqueryPredicate): 2924 pass 2925 2926 2927class Exists(SubqueryPredicate): 2928 pass 2929 2930 2931# Commands to interact with the databases or engines. For most of the command 2932# expressions we parse whatever comes after the command's name as a string. 2933class Command(Expression): 2934 arg_types = {"this": True, "expression": False} 2935 2936 2937class Transaction(Expression): 2938 arg_types = {"this": False, "modes": False} 2939 2940 2941class Commit(Expression): 2942 arg_types = {"chain": False} 2943 2944 2945class Rollback(Expression): 2946 arg_types = {"savepoint": False} 2947 2948 2949class AlterTable(Expression): 2950 arg_types = {"this": True, "actions": True, "exists": False} 2951 2952 2953class AddConstraint(Expression): 2954 arg_types = {"this": False, "expression": False, "enforced": False} 2955 2956 2957class DropPartition(Expression): 2958 arg_types = {"expressions": True, "exists": False} 2959 2960 2961# Binary expressions like (ADD a b) 2962class Binary(Expression): 2963 arg_types = {"this": True, "expression": True} 2964 2965 @property 2966 def left(self): 2967 return self.this 2968 2969 @property 2970 def right(self): 2971 return self.expression 2972 2973 2974class Add(Binary): 2975 pass 2976 2977 2978class Connector(Binary, Condition): 2979 pass 2980 2981 2982class And(Connector): 2983 pass 2984 2985 2986class Or(Connector): 2987 pass 2988 2989 2990class BitwiseAnd(Binary): 2991 pass 2992 2993 2994class BitwiseLeftShift(Binary): 2995 pass 2996 2997 2998class BitwiseOr(Binary): 2999 pass 3000 3001 3002class BitwiseRightShift(Binary): 3003 pass 3004 3005 3006class BitwiseXor(Binary): 3007 pass 3008 3009 3010class Div(Binary): 3011 pass 3012 3013 3014class Overlaps(Binary): 3015 pass 3016 3017 3018class Dot(Binary): 3019 @property 3020 def name(self) -> str: 3021 return self.expression.name 3022 3023 @classmethod 3024 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3025 """Build a Dot object with a sequence of expressions.""" 3026 if len(expressions) < 2: 3027 raise ValueError(f"Dot requires >= 2 expressions.") 3028 3029 a, b, *expressions = expressions 3030 dot = Dot(this=a, expression=b) 3031 3032 for expression in expressions: 3033 dot = Dot(this=dot, expression=expression) 3034 3035 return dot 3036 3037 3038class DPipe(Binary): 3039 pass 3040 3041 3042class EQ(Binary, Predicate): 3043 pass 3044 3045 3046class NullSafeEQ(Binary, Predicate): 3047 pass 3048 3049 3050class NullSafeNEQ(Binary, Predicate): 3051 pass 3052 3053 3054class Distance(Binary): 3055 pass 3056 3057 3058class Escape(Binary): 3059 pass 3060 3061 3062class Glob(Binary, Predicate): 3063 pass 3064 3065 3066class GT(Binary, Predicate): 3067 pass 3068 3069 3070class GTE(Binary, Predicate): 3071 pass 3072 3073 3074class ILike(Binary, Predicate): 3075 pass 3076 3077 3078class ILikeAny(Binary, Predicate): 3079 pass 3080 3081 3082class IntDiv(Binary): 3083 pass 3084 3085 3086class Is(Binary, Predicate): 3087 pass 3088 3089 3090class Kwarg(Binary): 3091 """Kwarg in special functions like func(kwarg => y).""" 3092 3093 3094class Like(Binary, Predicate): 3095 pass 3096 3097 3098class LikeAny(Binary, Predicate): 3099 pass 3100 3101 3102class LT(Binary, Predicate): 3103 pass 3104 3105 3106class LTE(Binary, Predicate): 3107 pass 3108 3109 3110class Mod(Binary): 3111 pass 3112 3113 3114class Mul(Binary): 3115 pass 3116 3117 3118class NEQ(Binary, Predicate): 3119 pass 3120 3121 3122class SimilarTo(Binary, Predicate): 3123 pass 3124 3125 3126class Slice(Binary): 3127 arg_types = {"this": False, "expression": False} 3128 3129 3130class Sub(Binary): 3131 pass 3132 3133 3134class ArrayOverlaps(Binary): 3135 pass 3136 3137 3138# Unary Expressions 3139# (NOT a) 3140class Unary(Expression): 3141 pass 3142 3143 3144class BitwiseNot(Unary): 3145 pass 3146 3147 3148class Not(Unary, Condition): 3149 pass 3150 3151 3152class Paren(Unary, Condition): 3153 arg_types = {"this": True, "with": False} 3154 3155 3156class Neg(Unary): 3157 pass 3158 3159 3160# Special Functions 3161class Alias(Expression): 3162 arg_types = {"this": True, "alias": False} 3163 3164 @property 3165 def output_name(self): 3166 return self.alias 3167 3168 3169class Aliases(Expression): 3170 arg_types = {"this": True, "expressions": True} 3171 3172 @property 3173 def aliases(self): 3174 return self.expressions 3175 3176 3177class AtTimeZone(Expression): 3178 arg_types = {"this": True, "zone": True} 3179 3180 3181class Between(Predicate): 3182 arg_types = {"this": True, "low": True, "high": True} 3183 3184 3185class Bracket(Condition): 3186 arg_types = {"this": True, "expressions": True} 3187 3188 3189class Distinct(Expression): 3190 arg_types = {"expressions": False, "on": False} 3191 3192 3193class In(Predicate): 3194 arg_types = { 3195 "this": True, 3196 "expressions": False, 3197 "query": False, 3198 "unnest": False, 3199 "field": False, 3200 "is_global": False, 3201 } 3202 3203 3204class TimeUnit(Expression): 3205 """Automatically converts unit arg into a var.""" 3206 3207 arg_types = {"unit": False} 3208 3209 def __init__(self, **args): 3210 unit = args.get("unit") 3211 if isinstance(unit, (Column, Literal)): 3212 args["unit"] = Var(this=unit.name) 3213 elif isinstance(unit, Week): 3214 unit.set("this", Var(this=unit.this.name)) 3215 super().__init__(**args) 3216 3217 3218class Interval(TimeUnit): 3219 arg_types = {"this": False, "unit": False} 3220 3221 3222class IgnoreNulls(Expression): 3223 pass 3224 3225 3226class RespectNulls(Expression): 3227 pass 3228 3229 3230# Functions 3231class Func(Condition): 3232 """ 3233 The base class for all function expressions. 3234 3235 Attributes: 3236 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3237 treated as a variable length argument and the argument's value will be stored as a list. 3238 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3239 for this function expression. These values are used to map this node to a name during parsing 3240 as well as to provide the function's name during SQL string generation. By default the SQL 3241 name is set to the expression's class name transformed to snake case. 3242 """ 3243 3244 is_var_len_args = False 3245 3246 @classmethod 3247 def from_arg_list(cls, args): 3248 if cls.is_var_len_args: 3249 all_arg_keys = list(cls.arg_types) 3250 # If this function supports variable length argument treat the last argument as such. 3251 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3252 num_non_var = len(non_var_len_arg_keys) 3253 3254 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3255 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3256 else: 3257 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3258 3259 return cls(**args_dict) 3260 3261 @classmethod 3262 def sql_names(cls): 3263 if cls is Func: 3264 raise NotImplementedError( 3265 "SQL name is only supported by concrete function implementations" 3266 ) 3267 if "_sql_names" not in cls.__dict__: 3268 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3269 return cls._sql_names 3270 3271 @classmethod 3272 def sql_name(cls): 3273 return cls.sql_names()[0] 3274 3275 @classmethod 3276 def default_parser_mappings(cls): 3277 return {name: cls.from_arg_list for name in cls.sql_names()} 3278 3279 3280class AggFunc(Func): 3281 pass 3282 3283 3284class Abs(Func): 3285 pass 3286 3287 3288class Anonymous(Func): 3289 arg_types = {"this": True, "expressions": False} 3290 is_var_len_args = True 3291 3292 3293class ApproxDistinct(AggFunc): 3294 arg_types = {"this": True, "accuracy": False} 3295 3296 3297class Array(Func): 3298 arg_types = {"expressions": False} 3299 is_var_len_args = True 3300 3301 3302# https://docs.snowflake.com/en/sql-reference/functions/to_char 3303class ToChar(Func): 3304 arg_types = {"this": True, "format": False} 3305 3306 3307class GenerateSeries(Func): 3308 arg_types = {"start": True, "end": True, "step": False} 3309 3310 3311class ArrayAgg(AggFunc): 3312 pass 3313 3314 3315class ArrayAll(Func): 3316 arg_types = {"this": True, "expression": True} 3317 3318 3319class ArrayAny(Func): 3320 arg_types = {"this": True, "expression": True} 3321 3322 3323class ArrayConcat(Func): 3324 arg_types = {"this": True, "expressions": False} 3325 is_var_len_args = True 3326 3327 3328class ArrayContains(Binary, Func): 3329 pass 3330 3331 3332class ArrayContained(Binary): 3333 pass 3334 3335 3336class ArrayFilter(Func): 3337 arg_types = {"this": True, "expression": True} 3338 _sql_names = ["FILTER", "ARRAY_FILTER"] 3339 3340 3341class ArrayJoin(Func): 3342 arg_types = {"this": True, "expression": True, "null": False} 3343 3344 3345class ArraySize(Func): 3346 arg_types = {"this": True, "expression": False} 3347 3348 3349class ArraySort(Func): 3350 arg_types = {"this": True, "expression": False} 3351 3352 3353class ArraySum(Func): 3354 pass 3355 3356 3357class ArrayUnionAgg(AggFunc): 3358 pass 3359 3360 3361class Avg(AggFunc): 3362 pass 3363 3364 3365class AnyValue(AggFunc): 3366 pass 3367 3368 3369class Case(Func): 3370 arg_types = {"this": False, "ifs": True, "default": False} 3371 3372 3373class Cast(Func): 3374 arg_types = {"this": True, "to": True} 3375 3376 @property 3377 def name(self) -> str: 3378 return self.this.name 3379 3380 @property 3381 def to(self): 3382 return self.args["to"] 3383 3384 @property 3385 def output_name(self): 3386 return self.name 3387 3388 def is_type(self, dtype: DataType.Type) -> bool: 3389 return self.to.is_type(dtype) 3390 3391 3392class Collate(Binary): 3393 pass 3394 3395 3396class TryCast(Cast): 3397 pass 3398 3399 3400class Ceil(Func): 3401 arg_types = {"this": True, "decimals": False} 3402 _sql_names = ["CEIL", "CEILING"] 3403 3404 3405class Coalesce(Func): 3406 arg_types = {"this": True, "expressions": False} 3407 is_var_len_args = True 3408 3409 3410class Concat(Func): 3411 arg_types = {"expressions": True} 3412 is_var_len_args = True 3413 3414 3415class ConcatWs(Concat): 3416 _sql_names = ["CONCAT_WS"] 3417 3418 3419class Count(AggFunc): 3420 arg_types = {"this": False} 3421 3422 3423class CountIf(AggFunc): 3424 pass 3425 3426 3427class CurrentDate(Func): 3428 arg_types = {"this": False} 3429 3430 3431class CurrentDatetime(Func): 3432 arg_types = {"this": False} 3433 3434 3435class CurrentTime(Func): 3436 arg_types = {"this": False} 3437 3438 3439class CurrentTimestamp(Func): 3440 arg_types = {"this": False} 3441 3442 3443class DateAdd(Func, TimeUnit): 3444 arg_types = {"this": True, "expression": True, "unit": False} 3445 3446 3447class DateSub(Func, TimeUnit): 3448 arg_types = {"this": True, "expression": True, "unit": False} 3449 3450 3451class DateDiff(Func, TimeUnit): 3452 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3453 arg_types = {"this": True, "expression": True, "unit": False} 3454 3455 3456class DateTrunc(Func): 3457 arg_types = {"unit": True, "this": True, "zone": False} 3458 3459 3460class DatetimeAdd(Func, TimeUnit): 3461 arg_types = {"this": True, "expression": True, "unit": False} 3462 3463 3464class DatetimeSub(Func, TimeUnit): 3465 arg_types = {"this": True, "expression": True, "unit": False} 3466 3467 3468class DatetimeDiff(Func, TimeUnit): 3469 arg_types = {"this": True, "expression": True, "unit": False} 3470 3471 3472class DatetimeTrunc(Func, TimeUnit): 3473 arg_types = {"this": True, "unit": True, "zone": False} 3474 3475 3476class DayOfWeek(Func): 3477 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3478 3479 3480class DayOfMonth(Func): 3481 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3482 3483 3484class DayOfYear(Func): 3485 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3486 3487 3488class WeekOfYear(Func): 3489 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3490 3491 3492class LastDateOfMonth(Func): 3493 pass 3494 3495 3496class Extract(Func): 3497 arg_types = {"this": True, "expression": True} 3498 3499 3500class TimestampAdd(Func, TimeUnit): 3501 arg_types = {"this": True, "expression": True, "unit": False} 3502 3503 3504class TimestampSub(Func, TimeUnit): 3505 arg_types = {"this": True, "expression": True, "unit": False} 3506 3507 3508class TimestampDiff(Func, TimeUnit): 3509 arg_types = {"this": True, "expression": True, "unit": False} 3510 3511 3512class TimestampTrunc(Func, TimeUnit): 3513 arg_types = {"this": True, "unit": True, "zone": False} 3514 3515 3516class TimeAdd(Func, TimeUnit): 3517 arg_types = {"this": True, "expression": True, "unit": False} 3518 3519 3520class TimeSub(Func, TimeUnit): 3521 arg_types = {"this": True, "expression": True, "unit": False} 3522 3523 3524class TimeDiff(Func, TimeUnit): 3525 arg_types = {"this": True, "expression": True, "unit": False} 3526 3527 3528class TimeTrunc(Func, TimeUnit): 3529 arg_types = {"this": True, "unit": True, "zone": False} 3530 3531 3532class DateFromParts(Func): 3533 _sql_names = ["DATEFROMPARTS"] 3534 arg_types = {"year": True, "month": True, "day": True} 3535 3536 3537class DateStrToDate(Func): 3538 pass 3539 3540 3541class DateToDateStr(Func): 3542 pass 3543 3544 3545class DateToDi(Func): 3546 pass 3547 3548 3549class Day(Func): 3550 pass 3551 3552 3553class Decode(Func): 3554 arg_types = {"this": True, "charset": True, "replace": False} 3555 3556 3557class DiToDate(Func): 3558 pass 3559 3560 3561class Encode(Func): 3562 arg_types = {"this": True, "charset": True} 3563 3564 3565class Exp(Func): 3566 pass 3567 3568 3569class Explode(Func): 3570 pass 3571 3572 3573class ExponentialTimeDecayedAvg(AggFunc): 3574 arg_types = {"this": True, "time": False, "decay": False} 3575 3576 3577class Floor(Func): 3578 arg_types = {"this": True, "decimals": False} 3579 3580 3581class Greatest(Func): 3582 arg_types = {"this": True, "expressions": False} 3583 is_var_len_args = True 3584 3585 3586class GroupConcat(Func): 3587 arg_types = {"this": True, "separator": False} 3588 3589 3590class GroupUniqArray(AggFunc): 3591 arg_types = {"this": True, "size": False} 3592 3593 3594class Hex(Func): 3595 pass 3596 3597 3598class Histogram(AggFunc): 3599 arg_types = {"this": True, "bins": False} 3600 3601 3602class If(Func): 3603 arg_types = {"this": True, "true": True, "false": False} 3604 3605 3606class IfNull(Func): 3607 arg_types = {"this": True, "expression": False} 3608 _sql_names = ["IFNULL", "NVL"] 3609 3610 3611class Initcap(Func): 3612 pass 3613 3614 3615class JSONKeyValue(Expression): 3616 arg_types = {"this": True, "expression": True} 3617 3618 3619class JSONObject(Func): 3620 arg_types = { 3621 "expressions": False, 3622 "null_handling": False, 3623 "unique_keys": False, 3624 "return_type": False, 3625 "format_json": False, 3626 "encoding": False, 3627 } 3628 3629 3630class JSONBContains(Binary): 3631 _sql_names = ["JSONB_CONTAINS"] 3632 3633 3634class JSONExtract(Binary, Func): 3635 _sql_names = ["JSON_EXTRACT"] 3636 3637 3638class JSONExtractScalar(JSONExtract): 3639 _sql_names = ["JSON_EXTRACT_SCALAR"] 3640 3641 3642class JSONBExtract(JSONExtract): 3643 _sql_names = ["JSONB_EXTRACT"] 3644 3645 3646class JSONBExtractScalar(JSONExtract): 3647 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3648 3649 3650class Least(Func): 3651 arg_types = {"expressions": False} 3652 is_var_len_args = True 3653 3654 3655class Length(Func): 3656 pass 3657 3658 3659class Levenshtein(Func): 3660 arg_types = { 3661 "this": True, 3662 "expression": False, 3663 "ins_cost": False, 3664 "del_cost": False, 3665 "sub_cost": False, 3666 } 3667 3668 3669class Ln(Func): 3670 pass 3671 3672 3673class Log(Func): 3674 arg_types = {"this": True, "expression": False} 3675 3676 3677class Log2(Func): 3678 pass 3679 3680 3681class Log10(Func): 3682 pass 3683 3684 3685class LogicalOr(AggFunc): 3686 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 3687 3688 3689class LogicalAnd(AggFunc): 3690 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 3691 3692 3693class Lower(Func): 3694 _sql_names = ["LOWER", "LCASE"] 3695 3696 3697class Map(Func): 3698 arg_types = {"keys": False, "values": False} 3699 3700 3701class VarMap(Func): 3702 arg_types = {"keys": True, "values": True} 3703 is_var_len_args = True 3704 3705 3706class Matches(Func): 3707 """Oracle/Snowflake decode. 3708 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3709 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3710 """ 3711 3712 arg_types = {"this": True, "expressions": True} 3713 is_var_len_args = True 3714 3715 3716class Max(AggFunc): 3717 arg_types = {"this": True, "expressions": False} 3718 is_var_len_args = True 3719 3720 3721class Min(AggFunc): 3722 arg_types = {"this": True, "expressions": False} 3723 is_var_len_args = True 3724 3725 3726class Month(Func): 3727 pass 3728 3729 3730class Nvl2(Func): 3731 arg_types = {"this": True, "true": True, "false": False} 3732 3733 3734class Posexplode(Func): 3735 pass 3736 3737 3738class Pow(Binary, Func): 3739 _sql_names = ["POWER", "POW"] 3740 3741 3742class PercentileCont(AggFunc): 3743 pass 3744 3745 3746class PercentileDisc(AggFunc): 3747 pass 3748 3749 3750class Quantile(AggFunc): 3751 arg_types = {"this": True, "quantile": True} 3752 3753 3754# Clickhouse-specific: 3755# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles 3756class Quantiles(AggFunc): 3757 arg_types = {"parameters": True, "expressions": True} 3758 is_var_len_args = True 3759 3760 3761class QuantileIf(AggFunc): 3762 arg_types = {"parameters": True, "expressions": True} 3763 3764 3765class ApproxQuantile(Quantile): 3766 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 3767 3768 3769class RangeN(Func): 3770 arg_types = {"this": True, "expressions": True, "each": False} 3771 3772 3773class ReadCSV(Func): 3774 _sql_names = ["READ_CSV"] 3775 is_var_len_args = True 3776 arg_types = {"this": True, "expressions": False} 3777 3778 3779class Reduce(Func): 3780 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 3781 3782 3783class RegexpExtract(Func): 3784 arg_types = { 3785 "this": True, 3786 "expression": True, 3787 "position": False, 3788 "occurrence": False, 3789 "group": False, 3790 } 3791 3792 3793class RegexpLike(Func): 3794 arg_types = {"this": True, "expression": True, "flag": False} 3795 3796 3797class RegexpILike(Func): 3798 arg_types = {"this": True, "expression": True, "flag": False} 3799 3800 3801# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 3802# limit is the number of times a pattern is applied 3803class RegexpSplit(Func): 3804 arg_types = {"this": True, "expression": True, "limit": False} 3805 3806 3807class Repeat(Func): 3808 arg_types = {"this": True, "times": True} 3809 3810 3811class Round(Func): 3812 arg_types = {"this": True, "decimals": False} 3813 3814 3815class RowNumber(Func): 3816 arg_types: t.Dict[str, t.Any] = {} 3817 3818 3819class SafeDivide(Func): 3820 arg_types = {"this": True, "expression": True} 3821 3822 3823class SetAgg(AggFunc): 3824 pass 3825 3826 3827class SortArray(Func): 3828 arg_types = {"this": True, "asc": False} 3829 3830 3831class Split(Func): 3832 arg_types = {"this": True, "expression": True, "limit": False} 3833 3834 3835# Start may be omitted in the case of postgres 3836# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 3837class Substring(Func): 3838 arg_types = {"this": True, "start": False, "length": False} 3839 3840 3841class StrPosition(Func): 3842 arg_types = { 3843 "this": True, 3844 "substr": True, 3845 "position": False, 3846 "instance": False, 3847 } 3848 3849 3850class StrToDate(Func): 3851 arg_types = {"this": True, "format": True} 3852 3853 3854class StrToTime(Func): 3855 arg_types = {"this": True, "format": True} 3856 3857 3858# Spark allows unix_timestamp() 3859# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 3860class StrToUnix(Func): 3861 arg_types = {"this": False, "format": False} 3862 3863 3864class NumberToStr(Func): 3865 arg_types = {"this": True, "format": True} 3866 3867 3868class Struct(Func): 3869 arg_types = {"expressions": True} 3870 is_var_len_args = True 3871 3872 3873class StructExtract(Func): 3874 arg_types = {"this": True, "expression": True} 3875 3876 3877class Sum(AggFunc): 3878 pass 3879 3880 3881class Sqrt(Func): 3882 pass 3883 3884 3885class Stddev(AggFunc): 3886 pass 3887 3888 3889class StddevPop(AggFunc): 3890 pass 3891 3892 3893class StddevSamp(AggFunc): 3894 pass 3895 3896 3897class TimeToStr(Func): 3898 arg_types = {"this": True, "format": True} 3899 3900 3901class TimeToTimeStr(Func): 3902 pass 3903 3904 3905class TimeToUnix(Func): 3906 pass 3907 3908 3909class TimeStrToDate(Func): 3910 pass 3911 3912 3913class TimeStrToTime(Func): 3914 pass 3915 3916 3917class TimeStrToUnix(Func): 3918 pass 3919 3920 3921class Trim(Func): 3922 arg_types = { 3923 "this": True, 3924 "expression": False, 3925 "position": False, 3926 "collation": False, 3927 } 3928 3929 3930class TsOrDsAdd(Func, TimeUnit): 3931 arg_types = {"this": True, "expression": True, "unit": False} 3932 3933 3934class TsOrDsToDateStr(Func): 3935 pass 3936 3937 3938class TsOrDsToDate(Func): 3939 arg_types = {"this": True, "format": False} 3940 3941 3942class TsOrDiToDi(Func): 3943 pass 3944 3945 3946class Unhex(Func): 3947 pass 3948 3949 3950class UnixToStr(Func): 3951 arg_types = {"this": True, "format": False} 3952 3953 3954# https://prestodb.io/docs/current/functions/datetime.html 3955# presto has weird zone/hours/minutes 3956class UnixToTime(Func): 3957 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3958 3959 SECONDS = Literal.string("seconds") 3960 MILLIS = Literal.string("millis") 3961 MICROS = Literal.string("micros") 3962 3963 3964class UnixToTimeStr(Func): 3965 pass 3966 3967 3968class Upper(Func): 3969 _sql_names = ["UPPER", "UCASE"] 3970 3971 3972class Variance(AggFunc): 3973 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 3974 3975 3976class VariancePop(AggFunc): 3977 _sql_names = ["VARIANCE_POP", "VAR_POP"] 3978 3979 3980class Week(Func): 3981 arg_types = {"this": True, "mode": False} 3982 3983 3984class XMLTable(Func): 3985 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 3986 3987 3988class Year(Func): 3989 pass 3990 3991 3992class Use(Expression): 3993 arg_types = {"this": True, "kind": False} 3994 3995 3996class Merge(Expression): 3997 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 3998 3999 4000class When(Func): 4001 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4002 4003 4004def _norm_arg(arg): 4005 return arg.lower() if type(arg) is str else arg 4006 4007 4008ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4009 4010 4011# Helpers 4012def maybe_parse( 4013 sql_or_expression: ExpOrStr, 4014 *, 4015 into: t.Optional[IntoType] = None, 4016 dialect: DialectType = None, 4017 prefix: t.Optional[str] = None, 4018 copy: bool = False, 4019 **opts, 4020) -> Expression: 4021 """Gracefully handle a possible string or expression. 4022 4023 Example: 4024 >>> maybe_parse("1") 4025 (LITERAL this: 1, is_string: False) 4026 >>> maybe_parse(to_identifier("x")) 4027 (IDENTIFIER this: x, quoted: False) 4028 4029 Args: 4030 sql_or_expression: the SQL code string or an expression 4031 into: the SQLGlot Expression to parse into 4032 dialect: the dialect used to parse the input expressions (in the case that an 4033 input expression is a SQL string). 4034 prefix: a string to prefix the sql with before it gets parsed 4035 (automatically includes a space) 4036 copy: whether or not to copy the expression. 4037 **opts: other options to use to parse the input expressions (again, in the case 4038 that an input expression is a SQL string). 4039 4040 Returns: 4041 Expression: the parsed or given expression. 4042 """ 4043 if isinstance(sql_or_expression, Expression): 4044 if copy: 4045 return sql_or_expression.copy() 4046 return sql_or_expression 4047 4048 import sqlglot 4049 4050 sql = str(sql_or_expression) 4051 if prefix: 4052 sql = f"{prefix} {sql}" 4053 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4054 4055 4056def _maybe_copy(instance, copy=True): 4057 return instance.copy() if copy else instance 4058 4059 4060def _is_wrong_expression(expression, into): 4061 return isinstance(expression, Expression) and not isinstance(expression, into) 4062 4063 4064def _apply_builder( 4065 expression, 4066 instance, 4067 arg, 4068 copy=True, 4069 prefix=None, 4070 into=None, 4071 dialect=None, 4072 **opts, 4073): 4074 if _is_wrong_expression(expression, into): 4075 expression = into(this=expression) 4076 instance = _maybe_copy(instance, copy) 4077 expression = maybe_parse( 4078 sql_or_expression=expression, 4079 prefix=prefix, 4080 into=into, 4081 dialect=dialect, 4082 **opts, 4083 ) 4084 instance.set(arg, expression) 4085 return instance 4086 4087 4088def _apply_child_list_builder( 4089 *expressions, 4090 instance, 4091 arg, 4092 append=True, 4093 copy=True, 4094 prefix=None, 4095 into=None, 4096 dialect=None, 4097 properties=None, 4098 **opts, 4099): 4100 instance = _maybe_copy(instance, copy) 4101 parsed = [] 4102 for expression in expressions: 4103 if _is_wrong_expression(expression, into): 4104 expression = into(expressions=[expression]) 4105 expression = maybe_parse( 4106 expression, 4107 into=into, 4108 dialect=dialect, 4109 prefix=prefix, 4110 **opts, 4111 ) 4112 parsed.extend(expression.expressions) 4113 4114 existing = instance.args.get(arg) 4115 if append and existing: 4116 parsed = existing.expressions + parsed 4117 4118 child = into(expressions=parsed) 4119 for k, v in (properties or {}).items(): 4120 child.set(k, v) 4121 instance.set(arg, child) 4122 return instance 4123 4124 4125def _apply_list_builder( 4126 *expressions, 4127 instance, 4128 arg, 4129 append=True, 4130 copy=True, 4131 prefix=None, 4132 into=None, 4133 dialect=None, 4134 **opts, 4135): 4136 inst = _maybe_copy(instance, copy) 4137 4138 expressions = [ 4139 maybe_parse( 4140 sql_or_expression=expression, 4141 into=into, 4142 prefix=prefix, 4143 dialect=dialect, 4144 **opts, 4145 ) 4146 for expression in expressions 4147 ] 4148 4149 existing_expressions = inst.args.get(arg) 4150 if append and existing_expressions: 4151 expressions = existing_expressions + expressions 4152 4153 inst.set(arg, expressions) 4154 return inst 4155 4156 4157def _apply_conjunction_builder( 4158 *expressions, 4159 instance, 4160 arg, 4161 into=None, 4162 append=True, 4163 copy=True, 4164 dialect=None, 4165 **opts, 4166): 4167 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4168 if not expressions: 4169 return instance 4170 4171 inst = _maybe_copy(instance, copy) 4172 4173 existing = inst.args.get(arg) 4174 if append and existing is not None: 4175 expressions = [existing.this if into else existing] + list(expressions) 4176 4177 node = and_(*expressions, dialect=dialect, **opts) 4178 4179 inst.set(arg, into(this=node) if into else node) 4180 return inst 4181 4182 4183def _combine(expressions, operator, dialect=None, **opts): 4184 expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions] 4185 this = expressions[0] 4186 if expressions[1:]: 4187 this = _wrap_operator(this) 4188 for expression in expressions[1:]: 4189 this = operator(this=this, expression=_wrap_operator(expression)) 4190 return this 4191 4192 4193def _wrap_operator(expression): 4194 if isinstance(expression, (And, Or, Not)): 4195 expression = Paren(this=expression) 4196 return expression 4197 4198 4199def union(left, right, distinct=True, dialect=None, **opts): 4200 """ 4201 Initializes a syntax tree from one UNION expression. 4202 4203 Example: 4204 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4205 'SELECT * FROM foo UNION SELECT * FROM bla' 4206 4207 Args: 4208 left (str | Expression): the SQL code string corresponding to the left-hand side. 4209 If an `Expression` instance is passed, it will be used as-is. 4210 right (str | Expression): the SQL code string corresponding to the right-hand side. 4211 If an `Expression` instance is passed, it will be used as-is. 4212 distinct (bool): set the DISTINCT flag if and only if this is true. 4213 dialect (str): the dialect used to parse the input expression. 4214 opts (kwargs): other options to use to parse the input expressions. 4215 Returns: 4216 Union: the syntax tree for the UNION expression. 4217 """ 4218 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4219 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4220 4221 return Union(this=left, expression=right, distinct=distinct) 4222 4223 4224def intersect(left, right, distinct=True, dialect=None, **opts): 4225 """ 4226 Initializes a syntax tree from one INTERSECT expression. 4227 4228 Example: 4229 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4230 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4231 4232 Args: 4233 left (str | Expression): the SQL code string corresponding to the left-hand side. 4234 If an `Expression` instance is passed, it will be used as-is. 4235 right (str | Expression): the SQL code string corresponding to the right-hand side. 4236 If an `Expression` instance is passed, it will be used as-is. 4237 distinct (bool): set the DISTINCT flag if and only if this is true. 4238 dialect (str): the dialect used to parse the input expression. 4239 opts (kwargs): other options to use to parse the input expressions. 4240 Returns: 4241 Intersect: the syntax tree for the INTERSECT expression. 4242 """ 4243 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4244 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4245 4246 return Intersect(this=left, expression=right, distinct=distinct) 4247 4248 4249def except_(left, right, distinct=True, dialect=None, **opts): 4250 """ 4251 Initializes a syntax tree from one EXCEPT expression. 4252 4253 Example: 4254 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4255 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4256 4257 Args: 4258 left (str | Expression): the SQL code string corresponding to the left-hand side. 4259 If an `Expression` instance is passed, it will be used as-is. 4260 right (str | Expression): the SQL code string corresponding to the right-hand side. 4261 If an `Expression` instance is passed, it will be used as-is. 4262 distinct (bool): set the DISTINCT flag if and only if this is true. 4263 dialect (str): the dialect used to parse the input expression. 4264 opts (kwargs): other options to use to parse the input expressions. 4265 Returns: 4266 Except: the syntax tree for the EXCEPT statement. 4267 """ 4268 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4269 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4270 4271 return Except(this=left, expression=right, distinct=distinct) 4272 4273 4274def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4275 """ 4276 Initializes a syntax tree from one or multiple SELECT expressions. 4277 4278 Example: 4279 >>> select("col1", "col2").from_("tbl").sql() 4280 'SELECT col1, col2 FROM tbl' 4281 4282 Args: 4283 *expressions: the SQL code string to parse as the expressions of a 4284 SELECT statement. If an Expression instance is passed, this is used as-is. 4285 dialect: the dialect used to parse the input expressions (in the case that an 4286 input expression is a SQL string). 4287 **opts: other options to use to parse the input expressions (again, in the case 4288 that an input expression is a SQL string). 4289 4290 Returns: 4291 Select: the syntax tree for the SELECT statement. 4292 """ 4293 return Select().select(*expressions, dialect=dialect, **opts) 4294 4295 4296def from_(*expressions, dialect=None, **opts) -> Select: 4297 """ 4298 Initializes a syntax tree from a FROM expression. 4299 4300 Example: 4301 >>> from_("tbl").select("col1", "col2").sql() 4302 'SELECT col1, col2 FROM tbl' 4303 4304 Args: 4305 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4306 SELECT statement. If an Expression instance is passed, this is used as-is. 4307 dialect (str): the dialect used to parse the input expression (in the case that the 4308 input expression is a SQL string). 4309 **opts: other options to use to parse the input expressions (again, in the case 4310 that the input expression is a SQL string). 4311 4312 Returns: 4313 Select: the syntax tree for the SELECT statement. 4314 """ 4315 return Select().from_(*expressions, dialect=dialect, **opts) 4316 4317 4318def update( 4319 table: str | Table, 4320 properties: dict, 4321 where: t.Optional[ExpOrStr] = None, 4322 from_: t.Optional[ExpOrStr] = None, 4323 dialect: DialectType = None, 4324 **opts, 4325) -> Update: 4326 """ 4327 Creates an update statement. 4328 4329 Example: 4330 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4331 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4332 4333 Args: 4334 *properties: dictionary of properties to set which are 4335 auto converted to sql objects eg None -> NULL 4336 where: sql conditional parsed into a WHERE statement 4337 from_: sql statement parsed into a FROM statement 4338 dialect: the dialect used to parse the input expressions. 4339 **opts: other options to use to parse the input expressions. 4340 4341 Returns: 4342 Update: the syntax tree for the UPDATE statement. 4343 """ 4344 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4345 update_expr.set( 4346 "expressions", 4347 [ 4348 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4349 for k, v in properties.items() 4350 ], 4351 ) 4352 if from_: 4353 update_expr.set( 4354 "from", 4355 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4356 ) 4357 if isinstance(where, Condition): 4358 where = Where(this=where) 4359 if where: 4360 update_expr.set( 4361 "where", 4362 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4363 ) 4364 return update_expr 4365 4366 4367def delete( 4368 table: ExpOrStr, 4369 where: t.Optional[ExpOrStr] = None, 4370 returning: t.Optional[ExpOrStr] = None, 4371 dialect: DialectType = None, 4372 **opts, 4373) -> Delete: 4374 """ 4375 Builds a delete statement. 4376 4377 Example: 4378 >>> delete("my_table", where="id > 1").sql() 4379 'DELETE FROM my_table WHERE id > 1' 4380 4381 Args: 4382 where: sql conditional parsed into a WHERE statement 4383 returning: sql conditional parsed into a RETURNING statement 4384 dialect: the dialect used to parse the input expressions. 4385 **opts: other options to use to parse the input expressions. 4386 4387 Returns: 4388 Delete: the syntax tree for the DELETE statement. 4389 """ 4390 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4391 if where: 4392 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4393 if returning: 4394 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4395 return delete_expr 4396 4397 4398def condition(expression, dialect=None, **opts) -> Condition: 4399 """ 4400 Initialize a logical condition expression. 4401 4402 Example: 4403 >>> condition("x=1").sql() 4404 'x = 1' 4405 4406 This is helpful for composing larger logical syntax trees: 4407 >>> where = condition("x=1") 4408 >>> where = where.and_("y=1") 4409 >>> Select().from_("tbl").select("*").where(where).sql() 4410 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4411 4412 Args: 4413 *expression (str | Expression): the SQL code string to parse. 4414 If an Expression instance is passed, this is used as-is. 4415 dialect (str): the dialect used to parse the input expression (in the case that the 4416 input expression is a SQL string). 4417 **opts: other options to use to parse the input expressions (again, in the case 4418 that the input expression is a SQL string). 4419 4420 Returns: 4421 Condition: the expression 4422 """ 4423 return maybe_parse( # type: ignore 4424 expression, 4425 into=Condition, 4426 dialect=dialect, 4427 **opts, 4428 ) 4429 4430 4431def and_(*expressions, dialect=None, **opts) -> And: 4432 """ 4433 Combine multiple conditions with an AND logical operator. 4434 4435 Example: 4436 >>> and_("x=1", and_("y=1", "z=1")).sql() 4437 'x = 1 AND (y = 1 AND z = 1)' 4438 4439 Args: 4440 *expressions (str | Expression): the SQL code strings to parse. 4441 If an Expression instance is passed, this is used as-is. 4442 dialect (str): the dialect used to parse the input expression. 4443 **opts: other options to use to parse the input expressions. 4444 4445 Returns: 4446 And: the new condition 4447 """ 4448 return _combine(expressions, And, dialect, **opts) 4449 4450 4451def or_(*expressions, dialect=None, **opts) -> Or: 4452 """ 4453 Combine multiple conditions with an OR logical operator. 4454 4455 Example: 4456 >>> or_("x=1", or_("y=1", "z=1")).sql() 4457 'x = 1 OR (y = 1 OR z = 1)' 4458 4459 Args: 4460 *expressions (str | Expression): the SQL code strings to parse. 4461 If an Expression instance is passed, this is used as-is. 4462 dialect (str): the dialect used to parse the input expression. 4463 **opts: other options to use to parse the input expressions. 4464 4465 Returns: 4466 Or: the new condition 4467 """ 4468 return _combine(expressions, Or, dialect, **opts) 4469 4470 4471def not_(expression, dialect=None, **opts) -> Not: 4472 """ 4473 Wrap a condition with a NOT operator. 4474 4475 Example: 4476 >>> not_("this_suit='black'").sql() 4477 "NOT this_suit = 'black'" 4478 4479 Args: 4480 expression (str | Expression): the SQL code strings to parse. 4481 If an Expression instance is passed, this is used as-is. 4482 dialect (str): the dialect used to parse the input expression. 4483 **opts: other options to use to parse the input expressions. 4484 4485 Returns: 4486 Not: the new condition 4487 """ 4488 this = condition( 4489 expression, 4490 dialect=dialect, 4491 **opts, 4492 ) 4493 return Not(this=_wrap_operator(this)) 4494 4495 4496def paren(expression) -> Paren: 4497 return Paren(this=expression) 4498 4499 4500SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4501 4502 4503@t.overload 4504def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None: 4505 ... 4506 4507 4508@t.overload 4509def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier: 4510 ... 4511 4512 4513def to_identifier(name, quoted=None): 4514 """Builds an identifier. 4515 4516 Args: 4517 name: The name to turn into an identifier. 4518 quoted: Whether or not force quote the identifier. 4519 4520 Returns: 4521 The identifier ast node. 4522 """ 4523 4524 if name is None: 4525 return None 4526 4527 if isinstance(name, Identifier): 4528 identifier = name 4529 elif isinstance(name, str): 4530 identifier = Identifier( 4531 this=name, 4532 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4533 ) 4534 else: 4535 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4536 return identifier 4537 4538 4539INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4540 4541 4542def to_interval(interval: str | Literal) -> Interval: 4543 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4544 if isinstance(interval, Literal): 4545 if not interval.is_string: 4546 raise ValueError("Invalid interval string.") 4547 4548 interval = interval.this 4549 4550 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4551 4552 if not interval_parts: 4553 raise ValueError("Invalid interval string.") 4554 4555 return Interval( 4556 this=Literal.string(interval_parts.group(1)), 4557 unit=Var(this=interval_parts.group(2)), 4558 ) 4559 4560 4561@t.overload 4562def to_table(sql_path: str | Table, **kwargs) -> Table: 4563 ... 4564 4565 4566@t.overload 4567def to_table(sql_path: None, **kwargs) -> None: 4568 ... 4569 4570 4571def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4572 """ 4573 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4574 If a table is passed in then that table is returned. 4575 4576 Args: 4577 sql_path: a `[catalog].[schema].[table]` string. 4578 4579 Returns: 4580 A table expression. 4581 """ 4582 if sql_path is None or isinstance(sql_path, Table): 4583 return sql_path 4584 if not isinstance(sql_path, str): 4585 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4586 4587 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4588 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 4589 4590 4591def to_column(sql_path: str | Column, **kwargs) -> Column: 4592 """ 4593 Create a column from a `[table].[column]` sql path. Schema is optional. 4594 4595 If a column is passed in then that column is returned. 4596 4597 Args: 4598 sql_path: `[table].[column]` string 4599 Returns: 4600 Table: A column expression 4601 """ 4602 if sql_path is None or isinstance(sql_path, Column): 4603 return sql_path 4604 if not isinstance(sql_path, str): 4605 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4606 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 4607 4608 4609def alias_( 4610 expression: ExpOrStr, 4611 alias: str | Identifier, 4612 table: bool | t.Sequence[str | Identifier] = False, 4613 quoted: t.Optional[bool] = None, 4614 dialect: DialectType = None, 4615 **opts, 4616): 4617 """Create an Alias expression. 4618 4619 Example: 4620 >>> alias_('foo', 'bar').sql() 4621 'foo AS bar' 4622 4623 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4624 '(SELECT 1, 2) AS bar(a, b)' 4625 4626 Args: 4627 expression: the SQL code strings to parse. 4628 If an Expression instance is passed, this is used as-is. 4629 alias: the alias name to use. If the name has 4630 special characters it is quoted. 4631 table: Whether or not to create a table alias, can also be a list of columns. 4632 quoted: whether or not to quote the alias 4633 dialect: the dialect used to parse the input expression. 4634 **opts: other options to use to parse the input expressions. 4635 4636 Returns: 4637 Alias: the aliased expression 4638 """ 4639 exp = maybe_parse(expression, dialect=dialect, **opts) 4640 alias = to_identifier(alias, quoted=quoted) 4641 4642 if table: 4643 table_alias = TableAlias(this=alias) 4644 exp.set("alias", table_alias) 4645 4646 if not isinstance(table, bool): 4647 for column in table: 4648 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4649 4650 return exp 4651 4652 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4653 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4654 # for the complete Window expression. 4655 # 4656 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4657 4658 if "alias" in exp.arg_types and not isinstance(exp, Window): 4659 exp = exp.copy() 4660 exp.set("alias", alias) 4661 return exp 4662 return Alias(this=exp, alias=alias) 4663 4664 4665def subquery(expression, alias=None, dialect=None, **opts): 4666 """ 4667 Build a subquery expression. 4668 4669 Example: 4670 >>> subquery('select x from tbl', 'bar').select('x').sql() 4671 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4672 4673 Args: 4674 expression (str | Expression): the SQL code strings to parse. 4675 If an Expression instance is passed, this is used as-is. 4676 alias (str | Expression): the alias name to use. 4677 dialect (str): the dialect used to parse the input expression. 4678 **opts: other options to use to parse the input expressions. 4679 4680 Returns: 4681 Select: a new select with the subquery expression included 4682 """ 4683 4684 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4685 return Select().from_(expression, dialect=dialect, **opts) 4686 4687 4688def column( 4689 col: str | Identifier, 4690 table: t.Optional[str | Identifier] = None, 4691 db: t.Optional[str | Identifier] = None, 4692 catalog: t.Optional[str | Identifier] = None, 4693 quoted: t.Optional[bool] = None, 4694) -> Column: 4695 """ 4696 Build a Column. 4697 4698 Args: 4699 col: column name 4700 table: table name 4701 db: db name 4702 catalog: catalog name 4703 quoted: whether or not to force quote each part 4704 Returns: 4705 Column: column instance 4706 """ 4707 return Column( 4708 this=to_identifier(col, quoted=quoted), 4709 table=to_identifier(table, quoted=quoted), 4710 db=to_identifier(db, quoted=quoted), 4711 catalog=to_identifier(catalog, quoted=quoted), 4712 ) 4713 4714 4715def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4716 """Cast an expression to a data type. 4717 4718 Example: 4719 >>> cast('x + 1', 'int').sql() 4720 'CAST(x + 1 AS INT)' 4721 4722 Args: 4723 expression: The expression to cast. 4724 to: The datatype to cast to. 4725 4726 Returns: 4727 A cast node. 4728 """ 4729 expression = maybe_parse(expression, **opts) 4730 return Cast(this=expression, to=DataType.build(to, **opts)) 4731 4732 4733def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4734 """Build a Table. 4735 4736 Args: 4737 table (str | Expression): column name 4738 db (str | Expression): db name 4739 catalog (str | Expression): catalog name 4740 4741 Returns: 4742 Table: table instance 4743 """ 4744 return Table( 4745 this=to_identifier(table, quoted=quoted), 4746 db=to_identifier(db, quoted=quoted), 4747 catalog=to_identifier(catalog, quoted=quoted), 4748 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4749 ) 4750 4751 4752def values( 4753 values: t.Iterable[t.Tuple[t.Any, ...]], 4754 alias: t.Optional[str] = None, 4755 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4756) -> Values: 4757 """Build VALUES statement. 4758 4759 Example: 4760 >>> values([(1, '2')]).sql() 4761 "VALUES (1, '2')" 4762 4763 Args: 4764 values: values statements that will be converted to SQL 4765 alias: optional alias 4766 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4767 If either are provided then an alias is also required. 4768 If a dictionary is provided then the first column of the values will be casted to the expected type 4769 in order to help with type inference. 4770 4771 Returns: 4772 Values: the Values expression object 4773 """ 4774 if columns and not alias: 4775 raise ValueError("Alias is required when providing columns") 4776 table_alias = ( 4777 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4778 if columns 4779 else TableAlias(this=to_identifier(alias) if alias else None) 4780 ) 4781 expressions = [convert(tup) for tup in values] 4782 if columns and isinstance(columns, dict): 4783 types = list(columns.values()) 4784 expressions[0].set( 4785 "expressions", 4786 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4787 ) 4788 return Values( 4789 expressions=expressions, 4790 alias=table_alias, 4791 ) 4792 4793 4794def var(name: t.Optional[ExpOrStr]) -> Var: 4795 """Build a SQL variable. 4796 4797 Example: 4798 >>> repr(var('x')) 4799 '(VAR this: x)' 4800 4801 >>> repr(var(column('x', table='y'))) 4802 '(VAR this: x)' 4803 4804 Args: 4805 name: The name of the var or an expression who's name will become the var. 4806 4807 Returns: 4808 The new variable node. 4809 """ 4810 if not name: 4811 raise ValueError("Cannot convert empty name into var.") 4812 4813 if isinstance(name, Expression): 4814 name = name.name 4815 return Var(this=name) 4816 4817 4818def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4819 """Build ALTER TABLE... RENAME... expression 4820 4821 Args: 4822 old_name: The old name of the table 4823 new_name: The new name of the table 4824 4825 Returns: 4826 Alter table expression 4827 """ 4828 old_table = to_table(old_name) 4829 new_table = to_table(new_name) 4830 return AlterTable( 4831 this=old_table, 4832 actions=[ 4833 RenameTable(this=new_table), 4834 ], 4835 ) 4836 4837 4838def convert(value) -> Expression: 4839 """Convert a python value into an expression object. 4840 4841 Raises an error if a conversion is not possible. 4842 4843 Args: 4844 value (Any): a python object 4845 4846 Returns: 4847 Expression: the equivalent expression object 4848 """ 4849 if isinstance(value, Expression): 4850 return value 4851 if value is None: 4852 return NULL 4853 if isinstance(value, bool): 4854 return Boolean(this=value) 4855 if isinstance(value, str): 4856 return Literal.string(value) 4857 if isinstance(value, float) and math.isnan(value): 4858 return NULL 4859 if isinstance(value, numbers.Number): 4860 return Literal.number(value) 4861 if isinstance(value, tuple): 4862 return Tuple(expressions=[convert(v) for v in value]) 4863 if isinstance(value, list): 4864 return Array(expressions=[convert(v) for v in value]) 4865 if isinstance(value, dict): 4866 return Map( 4867 keys=[convert(k) for k in value], 4868 values=[convert(v) for v in value.values()], 4869 ) 4870 if isinstance(value, datetime.datetime): 4871 datetime_literal = Literal.string( 4872 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4873 ) 4874 return TimeStrToTime(this=datetime_literal) 4875 if isinstance(value, datetime.date): 4876 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4877 return DateStrToDate(this=date_literal) 4878 raise ValueError(f"Cannot convert {value}") 4879 4880 4881def replace_children(expression, fun, *args, **kwargs): 4882 """ 4883 Replace children of an expression with the result of a lambda fun(child) -> exp. 4884 """ 4885 for k, v in expression.args.items(): 4886 is_list_arg = type(v) is list 4887 4888 child_nodes = v if is_list_arg else [v] 4889 new_child_nodes = [] 4890 4891 for cn in child_nodes: 4892 if isinstance(cn, Expression): 4893 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4894 new_child_nodes.append(child_node) 4895 child_node.parent = expression 4896 child_node.arg_key = k 4897 else: 4898 new_child_nodes.append(cn) 4899 4900 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 4901 4902 4903def column_table_names(expression): 4904 """ 4905 Return all table names referenced through columns in an expression. 4906 4907 Example: 4908 >>> import sqlglot 4909 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4910 ['c', 'a'] 4911 4912 Args: 4913 expression (sqlglot.Expression): expression to find table names 4914 4915 Returns: 4916 list: A list of unique names 4917 """ 4918 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 4919 4920 4921def table_name(table) -> str: 4922 """Get the full name of a table as a string. 4923 4924 Args: 4925 table (exp.Table | str): table expression node or string. 4926 4927 Examples: 4928 >>> from sqlglot import exp, parse_one 4929 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4930 'a.b.c' 4931 4932 Returns: 4933 The table name. 4934 """ 4935 4936 table = maybe_parse(table, into=Table) 4937 4938 if not table: 4939 raise ValueError(f"Cannot parse {table}") 4940 4941 return ".".join( 4942 part 4943 for part in ( 4944 table.text("catalog"), 4945 table.text("db"), 4946 table.name, 4947 ) 4948 if part 4949 ) 4950 4951 4952def replace_tables(expression, mapping): 4953 """Replace all tables in expression according to the mapping. 4954 4955 Args: 4956 expression (sqlglot.Expression): expression node to be transformed and replaced. 4957 mapping (Dict[str, str]): mapping of table names. 4958 4959 Examples: 4960 >>> from sqlglot import exp, parse_one 4961 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4962 'SELECT * FROM c' 4963 4964 Returns: 4965 The mapped expression. 4966 """ 4967 4968 def _replace_tables(node): 4969 if isinstance(node, Table): 4970 new_name = mapping.get(table_name(node)) 4971 if new_name: 4972 return to_table( 4973 new_name, 4974 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4975 ) 4976 return node 4977 4978 return expression.transform(_replace_tables) 4979 4980 4981def replace_placeholders(expression, *args, **kwargs): 4982 """Replace placeholders in an expression. 4983 4984 Args: 4985 expression (sqlglot.Expression): expression node to be transformed and replaced. 4986 args: positional names that will substitute unnamed placeholders in the given order. 4987 kwargs: keyword arguments that will substitute named placeholders. 4988 4989 Examples: 4990 >>> from sqlglot import exp, parse_one 4991 >>> replace_placeholders( 4992 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4993 ... ).sql() 4994 'SELECT * FROM foo WHERE a = b' 4995 4996 Returns: 4997 The mapped expression. 4998 """ 4999 5000 def _replace_placeholders(node, args, **kwargs): 5001 if isinstance(node, Placeholder): 5002 if node.name: 5003 new_name = kwargs.get(node.name) 5004 if new_name: 5005 return to_identifier(new_name) 5006 else: 5007 try: 5008 return to_identifier(next(args)) 5009 except StopIteration: 5010 pass 5011 return node 5012 5013 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5014 5015 5016def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 5017 """Transforms an expression by expanding all referenced sources into subqueries. 5018 5019 Examples: 5020 >>> from sqlglot import parse_one 5021 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5022 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5023 5024 Args: 5025 expression: The expression to expand. 5026 sources: A dictionary of name to Subqueryables. 5027 copy: Whether or not to copy the expression during transformation. Defaults to True. 5028 5029 Returns: 5030 The transformed expression. 5031 """ 5032 5033 def _expand(node: Expression): 5034 if isinstance(node, Table): 5035 name = table_name(node) 5036 source = sources.get(name) 5037 if source: 5038 subquery = source.subquery(node.alias or name) 5039 subquery.comments = [f"source: {name}"] 5040 return subquery 5041 return node 5042 5043 return expression.transform(_expand, copy=copy) 5044 5045 5046def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5047 """ 5048 Returns a Func expression. 5049 5050 Examples: 5051 >>> func("abs", 5).sql() 5052 'ABS(5)' 5053 5054 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5055 'CAST(5 AS DOUBLE)' 5056 5057 Args: 5058 name: the name of the function to build. 5059 args: the args used to instantiate the function of interest. 5060 dialect: the source dialect. 5061 kwargs: the kwargs used to instantiate the function of interest. 5062 5063 Note: 5064 The arguments `args` and `kwargs` are mutually exclusive. 5065 5066 Returns: 5067 An instance of the function of interest, or an anonymous function, if `name` doesn't 5068 correspond to an existing `sqlglot.expressions.Func` class. 5069 """ 5070 if args and kwargs: 5071 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5072 5073 from sqlglot.dialects.dialect import Dialect 5074 5075 converted = [convert(arg) for arg in args] 5076 kwargs = {key: convert(value) for key, value in kwargs.items()} 5077 5078 parser = Dialect.get_or_raise(dialect)().parser() 5079 from_args_list = parser.FUNCTIONS.get(name.upper()) 5080 5081 if from_args_list: 5082 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5083 else: 5084 kwargs = kwargs or {"expressions": converted} 5085 function = Anonymous(this=name, **kwargs) 5086 5087 for error_message in function.error_messages(converted): 5088 raise ValueError(error_message) 5089 5090 return function 5091 5092 5093def true(): 5094 """ 5095 Returns a true Boolean expression. 5096 """ 5097 return Boolean(this=True) 5098 5099 5100def false(): 5101 """ 5102 Returns a false Boolean expression. 5103 """ 5104 return Boolean(this=False) 5105 5106 5107def null(): 5108 """ 5109 Returns a Null expression. 5110 """ 5111 return Null() 5112 5113 5114# TODO: deprecate this 5115TRUE = Boolean(this=True) 5116FALSE = Boolean(this=False) 5117NULL = Null()
57class Expression(metaclass=_Expression): 58 """ 59 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 60 context, such as its child expressions, their names (arg keys), and whether a given child expression 61 is optional or not. 62 63 Attributes: 64 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 65 and representing expressions as strings. 66 arg_types: determines what arguments (child nodes) are supported by an expression. It 67 maps arg keys to booleans that indicate whether the corresponding args are optional. 68 69 Example: 70 >>> class Foo(Expression): 71 ... arg_types = {"this": True, "expression": False} 72 73 The above definition informs us that Foo is an Expression that requires an argument called 74 "this" and may also optionally receive an argument called "expression". 75 76 Args: 77 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 78 parent: a reference to the parent expression (or None, in case of root expressions). 79 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 80 uses to refer to it. 81 comments: a list of comments that are associated with a given expression. This is used in 82 order to preserve comments when transpiling SQL code. 83 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 84 optimizer, in order to enable some transformations that require type information. 85 """ 86 87 key = "expression" 88 arg_types = {"this": True} 89 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 90 91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value) 102 103 def __eq__(self, other) -> bool: 104 return type(self) is type(other) and hash(self) == hash(other) 105 106 @property 107 def hashable_args(self) -> t.Any: 108 args = (self.args.get(k) for k in self.arg_types) 109 110 return tuple( 111 (tuple(_norm_arg(a) for a in arg) if arg else None) 112 if type(arg) is list 113 else (_norm_arg(arg) if arg is not None and arg is not False else None) 114 for arg in args 115 ) 116 117 def __hash__(self) -> int: 118 if self._hash is not None: 119 return self._hash 120 121 return hash((self.__class__, self.hashable_args)) 122 123 @property 124 def this(self): 125 """ 126 Retrieves the argument with key "this". 127 """ 128 return self.args.get("this") 129 130 @property 131 def expression(self): 132 """ 133 Retrieves the argument with key "expression". 134 """ 135 return self.args.get("expression") 136 137 @property 138 def expressions(self): 139 """ 140 Retrieves the argument with key "expressions". 141 """ 142 return self.args.get("expressions") or [] 143 144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return "" 157 158 @property 159 def is_string(self) -> bool: 160 """ 161 Checks whether a Literal expression is a string. 162 """ 163 return isinstance(self, Literal) and self.args["is_string"] 164 165 @property 166 def is_number(self) -> bool: 167 """ 168 Checks whether a Literal expression is a number. 169 """ 170 return isinstance(self, Literal) and not self.args["is_string"] 171 172 @property 173 def is_int(self) -> bool: 174 """ 175 Checks whether a Literal expression is an integer. 176 """ 177 if self.is_number: 178 try: 179 int(self.name) 180 return True 181 except ValueError: 182 pass 183 return False 184 185 @property 186 def is_star(self) -> bool: 187 """Checks whether an expression is a star.""" 188 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 189 190 @property 191 def alias(self) -> str: 192 """ 193 Returns the alias of the expression, or an empty string if it's not aliased. 194 """ 195 if isinstance(self.args.get("alias"), TableAlias): 196 return self.args["alias"].name 197 return self.text("alias") 198 199 @property 200 def name(self) -> str: 201 return self.text("this") 202 203 @property 204 def alias_or_name(self): 205 return self.alias or self.name 206 207 @property 208 def output_name(self): 209 """ 210 Name of the output column if this expression is a selection. 211 212 If the Expression has no output name, an empty string is returned. 213 214 Example: 215 >>> from sqlglot import parse_one 216 >>> parse_one("SELECT a").expressions[0].output_name 217 'a' 218 >>> parse_one("SELECT b AS c").expressions[0].output_name 219 'c' 220 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 221 '' 222 """ 223 return "" 224 225 @property 226 def type(self) -> t.Optional[DataType]: 227 return self._type 228 229 @type.setter 230 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 231 if dtype and not isinstance(dtype, DataType): 232 dtype = DataType.build(dtype) 233 self._type = dtype # type: ignore 234 235 @property 236 def meta(self) -> t.Dict[str, t.Any]: 237 if self._meta is None: 238 self._meta = {} 239 return self._meta 240 241 def __deepcopy__(self, memo): 242 copy = self.__class__(**deepcopy(self.args)) 243 if self.comments is not None: 244 copy.comments = deepcopy(self.comments) 245 246 if self._type is not None: 247 copy._type = self._type.copy() 248 249 if self._meta is not None: 250 copy._meta = deepcopy(self._meta) 251 252 return copy 253 254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new 261 262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value) 274 275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value) 285 286 def _set_parent(self, arg_key, value): 287 if hasattr(value, "parent"): 288 value.parent = self 289 value.arg_key = arg_key 290 elif type(value) is list: 291 for v in value: 292 if hasattr(v, "parent"): 293 v.parent = self 294 v.arg_key = arg_key 295 296 @property 297 def depth(self): 298 """ 299 Returns the depth of this tree. 300 """ 301 if self.parent: 302 return self.parent.depth + 1 303 return 0 304 305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs 315 316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None) 328 329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression 343 344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor) 358 359 @property 360 def parent_select(self): 361 """ 362 Returns the parent select statement. 363 """ 364 return self.find_ancestor(Select) 365 366 @property 367 def same_parent(self): 368 """Returns if the parent is the same class as itself.""" 369 return type(self.parent) is self.__class__ 370 371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression 379 380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune) 397 398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune) 413 414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k)) 433 434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression 442 443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self 450 451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 456 457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node 466 467 def __str__(self): 468 return self.sql() 469 470 def __repr__(self): 471 return self._to_s() 472 473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts) 487 488 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 489 indent = "" if not level else "\n" 490 indent += "".join([" "] * level) 491 left = f"({self.key.upper()} " 492 493 args: t.Dict[str, t.Any] = { 494 k: ", ".join( 495 v._to_s(hide_missing=hide_missing, level=level + 1) 496 if hasattr(v, "_to_s") 497 else str(v) 498 for v in ensure_list(vs) 499 if v is not None 500 ) 501 for k, vs in self.args.items() 502 } 503 args["comments"] = self.comments 504 args["type"] = self.type 505 args = {k: v for k, v in args.items() if v or not hide_missing} 506 507 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 508 right += ")" 509 510 return indent + left + right 511 512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node 538 539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression 565 566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self 575 576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self 592 593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors 626 627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self) 634 635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataTypetype of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value)
144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new
Returns a deep copy of the expression.
262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value)
Sets arg_key to value.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs
Yields the key and expression for all arguments, exploding list args.
316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The node which matches the criteria or None if no such node was found.
329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The generator object.
344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression
Returns the root expression of this tree.
380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression
Returns the first non parenthesis child or self.
443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self
Returns the inner expression if this is an Alias.
451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generatoroptions.
Returns:
The SQL string.
512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression (Expression|None): new node
Returns:
The new expression or expressions.
566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self
Remove this expression from its AST.
Returns:
The popped expression.
576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self
Assert that this Expression is an instance of type_.
If it is NOT an instance of type_, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self)
Dump this Expression to a JSON-serializable dict.
635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
Load a dict (as returned by Expression.dump) into an Expression instance.
653class Condition(Expression): 654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts) 672 673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts) 691 692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Returns:
Not: the new condition.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
710class DerivedTable(Expression): 711 @property 712 def alias_column_names(self): 713 table_alias = self.args.get("alias") 714 if not table_alias: 715 return [] 716 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 717 return [c.name for c in column_list] 718 719 @property 720 def selects(self): 721 alias = self.args.get("alias") 722 723 if alias: 724 return alias.columns 725 return [] 726 727 @property 728 def named_selects(self): 729 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
732class Unionable(Expression): 733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 752 753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 772 773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the Union expression.
753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the Intersect expression
773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the Except expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
798class Cache(Expression): 799 arg_types = { 800 "with": False, 801 "this": True, 802 "lazy": False, 803 "options": False, 804 "expression": False, 805 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
812class Create(Expression): 813 arg_types = { 814 "with": False, 815 "this": True, 816 "kind": True, 817 "expression": False, 818 "exists": False, 819 "properties": False, 820 "replace": False, 821 "unique": False, 822 "volatile": False, 823 "indexes": False, 824 "no_schema_binding": False, 825 "begin": False, 826 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
841class SetItem(Expression): 842 arg_types = { 843 "this": False, 844 "expressions": False, 845 "kind": False, 846 "collate": False, # MySQL SET NAMES statement 847 "global": False, 848 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
851class Show(Expression): 852 arg_types = { 853 "this": True, 854 "target": False, 855 "offset": False, 856 "limit": False, 857 "like": False, 858 "where": False, 859 "db": False, 860 "full": False, 861 "mutex": False, 862 "query": False, 863 "channel": False, 864 "global": False, 865 "log": False, 866 "position": False, 867 "types": False, 868 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
871class UserDefinedFunction(Expression): 872 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
879class With(Expression): 880 arg_types = {"expressions": True, "recursive": False} 881 882 @property 883 def recursive(self) -> bool: 884 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
895class TableAlias(Expression): 896 arg_types = {"this": False, "columns": False} 897 898 @property 899 def columns(self): 900 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
915class Column(Condition): 916 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 917 918 @property 919 def table(self) -> str: 920 return self.text("table") 921 922 @property 923 def db(self) -> str: 924 return self.text("db") 925 926 @property 927 def catalog(self) -> str: 928 return self.text("catalog") 929 930 @property 931 def output_name(self) -> str: 932 return self.name 933 934 @property 935 def parts(self) -> t.List[Identifier]: 936 """Return the parts of a column in order catalog, db, table, name.""" 937 return [part for part in reversed(list(self.args.values())) if part] 938 939 def to_dot(self) -> Dot: 940 """Converts the column into a dot expression.""" 941 parts = self.parts 942 parent = self.parent 943 944 while parent: 945 if isinstance(parent, Dot): 946 parts.append(parent.expression) 947 parent = parent.parent 948 949 return Dot.build(parts)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Return the parts of a column in order catalog, db, table, name.
939 def to_dot(self) -> Dot: 940 """Converts the column into a dot expression.""" 941 parts = self.parts 942 parent = self.parent 943 944 while parent: 945 if isinstance(parent, Dot): 946 parts.append(parent.expression) 947 parent = parent.parent 948 949 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
952class ColumnDef(Expression): 953 arg_types = { 954 "this": True, 955 "kind": False, 956 "constraints": False, 957 "exists": False, 958 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
961class AlterColumn(Expression): 962 arg_types = { 963 "this": True, 964 "dtype": False, 965 "collate": False, 966 "using": False, 967 "default": False, 968 "drop": False, 969 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
980class Comment(Expression): 981 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1032class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1033 # this: True -> ALWAYS, this: False -> BY DEFAULT 1034 arg_types = { 1035 "this": False, 1036 "start": False, 1037 "increment": False, 1038 "minvalue": False, 1039 "maxvalue": False, 1040 "cycle": False, 1041 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1076class Delete(Expression): 1077 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1078 1079 def delete( 1080 self, 1081 table: ExpOrStr, 1082 dialect: DialectType = None, 1083 copy: bool = True, 1084 **opts, 1085 ) -> Delete: 1086 """ 1087 Create a DELETE expression or replace the table on an existing DELETE expression. 1088 1089 Example: 1090 >>> delete("tbl").sql() 1091 'DELETE FROM tbl' 1092 1093 Args: 1094 table: the table from which to delete. 1095 dialect: the dialect used to parse the input expression. 1096 copy: if `False`, modify this expression instance in-place. 1097 opts: other options to use to parse the input expressions. 1098 1099 Returns: 1100 Delete: the modified expression. 1101 """ 1102 return _apply_builder( 1103 expression=table, 1104 instance=self, 1105 arg="this", 1106 dialect=dialect, 1107 into=Table, 1108 copy=copy, 1109 **opts, 1110 ) 1111 1112 def where( 1113 self, 1114 *expressions: ExpOrStr, 1115 append: bool = True, 1116 dialect: DialectType = None, 1117 copy: bool = True, 1118 **opts, 1119 ) -> Delete: 1120 """ 1121 Append to or set the WHERE expressions. 1122 1123 Example: 1124 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1125 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1126 1127 Args: 1128 *expressions: the SQL code strings to parse. 1129 If an `Expression` instance is passed, it will be used as-is. 1130 Multiple expressions are combined with an AND operator. 1131 append: if `True`, AND the new expressions to any existing expression. 1132 Otherwise, this resets the expression. 1133 dialect: the dialect used to parse the input expressions. 1134 copy: if `False`, modify this expression instance in-place. 1135 opts: other options to use to parse the input expressions. 1136 1137 Returns: 1138 Delete: the modified expression. 1139 """ 1140 return _apply_conjunction_builder( 1141 *expressions, 1142 instance=self, 1143 arg="where", 1144 append=append, 1145 into=Where, 1146 dialect=dialect, 1147 copy=copy, 1148 **opts, 1149 ) 1150 1151 def returning( 1152 self, 1153 expression: ExpOrStr, 1154 dialect: DialectType = None, 1155 copy: bool = True, 1156 **opts, 1157 ) -> Delete: 1158 """ 1159 Set the RETURNING expression. Not supported by all dialects. 1160 1161 Example: 1162 >>> delete("tbl").returning("*", dialect="postgres").sql() 1163 'DELETE FROM tbl RETURNING *' 1164 1165 Args: 1166 expression: the SQL code strings to parse. 1167 If an `Expression` instance is passed, it will be used as-is. 1168 dialect: the dialect used to parse the input expressions. 1169 copy: if `False`, modify this expression instance in-place. 1170 opts: other options to use to parse the input expressions. 1171 1172 Returns: 1173 Delete: the modified expression. 1174 """ 1175 return _apply_builder( 1176 expression=expression, 1177 instance=self, 1178 arg="returning", 1179 prefix="RETURNING", 1180 dialect=dialect, 1181 copy=copy, 1182 into=Returning, 1183 **opts, 1184 )
1079 def delete( 1080 self, 1081 table: ExpOrStr, 1082 dialect: DialectType = None, 1083 copy: bool = True, 1084 **opts, 1085 ) -> Delete: 1086 """ 1087 Create a DELETE expression or replace the table on an existing DELETE expression. 1088 1089 Example: 1090 >>> delete("tbl").sql() 1091 'DELETE FROM tbl' 1092 1093 Args: 1094 table: the table from which to delete. 1095 dialect: the dialect used to parse the input expression. 1096 copy: if `False`, modify this expression instance in-place. 1097 opts: other options to use to parse the input expressions. 1098 1099 Returns: 1100 Delete: the modified expression. 1101 """ 1102 return _apply_builder( 1103 expression=table, 1104 instance=self, 1105 arg="this", 1106 dialect=dialect, 1107 into=Table, 1108 copy=copy, 1109 **opts, 1110 )
Create a DELETE expression or replace the table on an existing DELETE expression.
Example:
>>> delete("tbl").sql() 'DELETE FROM tbl'
Arguments:
- table: the table from which to delete.
- dialect: the dialect used to parse the input expression.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1112 def where( 1113 self, 1114 *expressions: ExpOrStr, 1115 append: bool = True, 1116 dialect: DialectType = None, 1117 copy: bool = True, 1118 **opts, 1119 ) -> Delete: 1120 """ 1121 Append to or set the WHERE expressions. 1122 1123 Example: 1124 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1125 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1126 1127 Args: 1128 *expressions: the SQL code strings to parse. 1129 If an `Expression` instance is passed, it will be used as-is. 1130 Multiple expressions are combined with an AND operator. 1131 append: if `True`, AND the new expressions to any existing expression. 1132 Otherwise, this resets the expression. 1133 dialect: the dialect used to parse the input expressions. 1134 copy: if `False`, modify this expression instance in-place. 1135 opts: other options to use to parse the input expressions. 1136 1137 Returns: 1138 Delete: the modified expression. 1139 """ 1140 return _apply_conjunction_builder( 1141 *expressions, 1142 instance=self, 1143 arg="where", 1144 append=append, 1145 into=Where, 1146 dialect=dialect, 1147 copy=copy, 1148 **opts, 1149 )
Append to or set the WHERE expressions.
Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1151 def returning( 1152 self, 1153 expression: ExpOrStr, 1154 dialect: DialectType = None, 1155 copy: bool = True, 1156 **opts, 1157 ) -> Delete: 1158 """ 1159 Set the RETURNING expression. Not supported by all dialects. 1160 1161 Example: 1162 >>> delete("tbl").returning("*", dialect="postgres").sql() 1163 'DELETE FROM tbl RETURNING *' 1164 1165 Args: 1166 expression: the SQL code strings to parse. 1167 If an `Expression` instance is passed, it will be used as-is. 1168 dialect: the dialect used to parse the input expressions. 1169 copy: if `False`, modify this expression instance in-place. 1170 opts: other options to use to parse the input expressions. 1171 1172 Returns: 1173 Delete: the modified expression. 1174 """ 1175 return _apply_builder( 1176 expression=expression, 1177 instance=self, 1178 arg="returning", 1179 prefix="RETURNING", 1180 dialect=dialect, 1181 copy=copy, 1182 into=Returning, 1183 **opts, 1184 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1187class Drop(Expression): 1188 arg_types = { 1189 "this": False, 1190 "kind": False, 1191 "exists": False, 1192 "temporary": False, 1193 "materialized": False, 1194 "cascade": False, 1195 "constraints": False, 1196 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1207class Directory(Expression): 1208 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1209 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1212class ForeignKey(Expression): 1213 arg_types = { 1214 "expressions": True, 1215 "reference": False, 1216 "delete": False, 1217 "update": False, 1218 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1251class Identifier(Expression): 1252 arg_types = {"this": True, "quoted": False} 1253 1254 @property 1255 def quoted(self): 1256 return bool(self.args.get("quoted")) 1257 1258 @property 1259 def hashable_args(self) -> t.Any: 1260 if self.quoted and any(char.isupper() for char in self.this): 1261 return (self.this, self.quoted) 1262 return self.this.lower() 1263 1264 @property 1265 def output_name(self): 1266 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1269class Index(Expression): 1270 arg_types = { 1271 "this": False, 1272 "table": False, 1273 "where": False, 1274 "columns": False, 1275 "unique": False, 1276 "primary": False, 1277 "amp": False, # teradata 1278 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1281class Insert(Expression): 1282 arg_types = { 1283 "with": False, 1284 "this": True, 1285 "expression": False, 1286 "returning": False, 1287 "overwrite": False, 1288 "exists": False, 1289 "partition": False, 1290 "alternative": False, 1291 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1308class LoadData(Expression): 1309 arg_types = { 1310 "this": True, 1311 "local": False, 1312 "overwrite": False, 1313 "inpath": True, 1314 "partition": False, 1315 "input_format": False, 1316 "serde": False, 1317 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1328class Group(Expression): 1329 arg_types = { 1330 "expressions": False, 1331 "grouping_sets": False, 1332 "cube": False, 1333 "rollup": False, 1334 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1345class Literal(Condition): 1346 arg_types = {"this": True, "is_string": True} 1347 1348 @property 1349 def hashable_args(self) -> t.Any: 1350 return (self.this, self.args.get("is_string")) 1351 1352 @classmethod 1353 def number(cls, number) -> Literal: 1354 return cls(this=str(number), is_string=False) 1355 1356 @classmethod 1357 def string(cls, string) -> Literal: 1358 return cls(this=str(string), is_string=True) 1359 1360 @property 1361 def output_name(self): 1362 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1365class Join(Expression): 1366 arg_types = { 1367 "this": True, 1368 "on": False, 1369 "side": False, 1370 "kind": False, 1371 "using": False, 1372 "natural": False, 1373 } 1374 1375 @property 1376 def kind(self): 1377 return self.text("kind").upper() 1378 1379 @property 1380 def side(self): 1381 return self.text("side").upper() 1382 1383 @property 1384 def alias_or_name(self): 1385 return self.this.alias_or_name 1386 1387 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1388 """ 1389 Append to or set the ON expressions. 1390 1391 Example: 1392 >>> import sqlglot 1393 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1394 'JOIN x ON y = 1' 1395 1396 Args: 1397 *expressions (str | Expression): the SQL code strings to parse. 1398 If an `Expression` instance is passed, it will be used as-is. 1399 Multiple expressions are combined with an AND operator. 1400 append (bool): if `True`, AND the new expressions to any existing expression. 1401 Otherwise, this resets the expression. 1402 dialect (str): the dialect used to parse the input expressions. 1403 copy (bool): if `False`, modify this expression instance in-place. 1404 opts (kwargs): other options to use to parse the input expressions. 1405 1406 Returns: 1407 Join: the modified join expression. 1408 """ 1409 join = _apply_conjunction_builder( 1410 *expressions, 1411 instance=self, 1412 arg="on", 1413 append=append, 1414 dialect=dialect, 1415 copy=copy, 1416 **opts, 1417 ) 1418 1419 if join.kind == "CROSS": 1420 join.set("kind", None) 1421 1422 return join 1423 1424 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1425 """ 1426 Append to or set the USING expressions. 1427 1428 Example: 1429 >>> import sqlglot 1430 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1431 'JOIN x USING (foo, bla)' 1432 1433 Args: 1434 *expressions (str | Expression): the SQL code strings to parse. 1435 If an `Expression` instance is passed, it will be used as-is. 1436 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1437 Otherwise, this resets the expression. 1438 dialect (str): the dialect used to parse the input expressions. 1439 copy (bool): if `False`, modify this expression instance in-place. 1440 opts (kwargs): other options to use to parse the input expressions. 1441 1442 Returns: 1443 Join: the modified join expression. 1444 """ 1445 join = _apply_list_builder( 1446 *expressions, 1447 instance=self, 1448 arg="using", 1449 append=append, 1450 dialect=dialect, 1451 copy=copy, 1452 **opts, 1453 ) 1454 1455 if join.kind == "CROSS": 1456 join.set("kind", None) 1457 1458 return join
1387 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1388 """ 1389 Append to or set the ON expressions. 1390 1391 Example: 1392 >>> import sqlglot 1393 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1394 'JOIN x ON y = 1' 1395 1396 Args: 1397 *expressions (str | Expression): the SQL code strings to parse. 1398 If an `Expression` instance is passed, it will be used as-is. 1399 Multiple expressions are combined with an AND operator. 1400 append (bool): if `True`, AND the new expressions to any existing expression. 1401 Otherwise, this resets the expression. 1402 dialect (str): the dialect used to parse the input expressions. 1403 copy (bool): if `False`, modify this expression instance in-place. 1404 opts (kwargs): other options to use to parse the input expressions. 1405 1406 Returns: 1407 Join: the modified join expression. 1408 """ 1409 join = _apply_conjunction_builder( 1410 *expressions, 1411 instance=self, 1412 arg="on", 1413 append=append, 1414 dialect=dialect, 1415 copy=copy, 1416 **opts, 1417 ) 1418 1419 if join.kind == "CROSS": 1420 join.set("kind", None) 1421 1422 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
1424 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1425 """ 1426 Append to or set the USING expressions. 1427 1428 Example: 1429 >>> import sqlglot 1430 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1431 'JOIN x USING (foo, bla)' 1432 1433 Args: 1434 *expressions (str | Expression): the SQL code strings to parse. 1435 If an `Expression` instance is passed, it will be used as-is. 1436 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1437 Otherwise, this resets the expression. 1438 dialect (str): the dialect used to parse the input expressions. 1439 copy (bool): if `False`, modify this expression instance in-place. 1440 opts (kwargs): other options to use to parse the input expressions. 1441 1442 Returns: 1443 Join: the modified join expression. 1444 """ 1445 join = _apply_list_builder( 1446 *expressions, 1447 instance=self, 1448 arg="using", 1449 append=append, 1450 dialect=dialect, 1451 copy=copy, 1452 **opts, 1453 ) 1454 1455 if join.kind == "CROSS": 1456 join.set("kind", None) 1457 1458 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1461class Lateral(UDTF): 1462 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1465class MatchRecognize(Expression): 1466 arg_types = { 1467 "partition_by": False, 1468 "order": False, 1469 "measures": False, 1470 "rows": False, 1471 "after": False, 1472 "pattern": False, 1473 "define": False, 1474 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1513class AfterJournalProperty(Property): 1514 arg_types = {"no": True, "dual": False, "local": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1525class BlockCompressionProperty(Property): 1526 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1541class DataBlocksizeProperty(Property): 1542 arg_types = {"size": False, "units": False, "min": False, "default": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1581class IsolatedLoadingProperty(Property): 1582 arg_types = { 1583 "no": True, 1584 "concurrent": True, 1585 "for_all": True, 1586 "for_insert": True, 1587 "for_none": True, 1588 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1607class LockingProperty(Property): 1608 arg_types = { 1609 "this": False, 1610 "kind": True, 1611 "for_or_in": True, 1612 "lock_type": True, 1613 "override": False, 1614 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1625class MergeBlockRatioProperty(Property): 1626 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1641class ReturnsProperty(Property): 1642 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1645class RowFormatDelimitedProperty(Property): 1646 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1647 arg_types = { 1648 "fields": False, 1649 "escaped": False, 1650 "collection_items": False, 1651 "map_keys": False, 1652 "lines": False, 1653 "null": False, 1654 "serde": False, 1655 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1706class Properties(Expression): 1707 arg_types = {"expressions": True} 1708 1709 NAME_TO_PROPERTY = { 1710 "ALGORITHM": AlgorithmProperty, 1711 "AUTO_INCREMENT": AutoIncrementProperty, 1712 "CHARACTER SET": CharacterSetProperty, 1713 "COLLATE": CollateProperty, 1714 "COMMENT": SchemaCommentProperty, 1715 "DEFINER": DefinerProperty, 1716 "DISTKEY": DistKeyProperty, 1717 "DISTSTYLE": DistStyleProperty, 1718 "ENGINE": EngineProperty, 1719 "EXECUTE AS": ExecuteAsProperty, 1720 "FORMAT": FileFormatProperty, 1721 "LANGUAGE": LanguageProperty, 1722 "LOCATION": LocationProperty, 1723 "PARTITIONED_BY": PartitionedByProperty, 1724 "RETURNS": ReturnsProperty, 1725 "SORTKEY": SortKeyProperty, 1726 "TABLE_FORMAT": TableFormatProperty, 1727 } 1728 1729 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1730 1731 # CREATE property locations 1732 # Form: schema specified 1733 # create [POST_CREATE] 1734 # table a [POST_NAME] 1735 # (b int) [POST_SCHEMA] 1736 # with ([POST_WITH]) 1737 # index (b) [POST_INDEX] 1738 # 1739 # Form: alias selection 1740 # create [POST_CREATE] 1741 # table a [POST_NAME] 1742 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1743 # index (c) [POST_INDEX] 1744 class Location(AutoName): 1745 POST_CREATE = auto() 1746 POST_NAME = auto() 1747 POST_SCHEMA = auto() 1748 POST_WITH = auto() 1749 POST_ALIAS = auto() 1750 POST_EXPRESSION = auto() 1751 POST_INDEX = auto() 1752 UNSUPPORTED = auto() 1753 1754 @classmethod 1755 def from_dict(cls, properties_dict) -> Properties: 1756 expressions = [] 1757 for key, value in properties_dict.items(): 1758 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1759 if property_cls: 1760 expressions.append(property_cls(this=convert(value))) 1761 else: 1762 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1763 1764 return cls(expressions=expressions)
1754 @classmethod 1755 def from_dict(cls, properties_dict) -> Properties: 1756 expressions = [] 1757 for key, value in properties_dict.items(): 1758 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1759 if property_cls: 1760 expressions.append(property_cls(this=convert(value))) 1761 else: 1762 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1763 1764 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1744 class Location(AutoName): 1745 POST_CREATE = auto() 1746 POST_NAME = auto() 1747 POST_SCHEMA = auto() 1748 POST_WITH = auto() 1749 POST_ALIAS = auto() 1750 POST_EXPRESSION = auto() 1751 POST_INDEX = auto() 1752 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1776class Reference(Expression): 1777 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1784class Subqueryable(Unionable): 1785 def subquery(self, alias=None, copy=True) -> Subquery: 1786 """ 1787 Convert this expression to an aliased expression that can be used as a Subquery. 1788 1789 Example: 1790 >>> subquery = Select().select("x").from_("tbl").subquery() 1791 >>> Select().select("x").from_(subquery).sql() 1792 'SELECT x FROM (SELECT x FROM tbl)' 1793 1794 Args: 1795 alias (str | Identifier): an optional alias for the subquery 1796 copy (bool): if `False`, modify this expression instance in-place. 1797 1798 Returns: 1799 Alias: the subquery 1800 """ 1801 instance = _maybe_copy(self, copy) 1802 return Subquery( 1803 this=instance, 1804 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1805 ) 1806 1807 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1808 raise NotImplementedError 1809 1810 @property 1811 def ctes(self): 1812 with_ = self.args.get("with") 1813 if not with_: 1814 return [] 1815 return with_.expressions 1816 1817 @property 1818 def selects(self): 1819 raise NotImplementedError("Subqueryable objects must implement `selects`") 1820 1821 @property 1822 def named_selects(self): 1823 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1824 1825 def with_( 1826 self, 1827 alias, 1828 as_, 1829 recursive=None, 1830 append=True, 1831 dialect=None, 1832 copy=True, 1833 **opts, 1834 ): 1835 """ 1836 Append to or set the common table expressions. 1837 1838 Example: 1839 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1840 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1841 1842 Args: 1843 alias (str | Expression): the SQL code string to parse as the table name. 1844 If an `Expression` instance is passed, this is used as-is. 1845 as_ (str | Expression): the SQL code string to parse as the table expression. 1846 If an `Expression` instance is passed, it will be used as-is. 1847 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1848 append (bool): if `True`, add to any existing expressions. 1849 Otherwise, this resets the expressions. 1850 dialect (str): the dialect used to parse the input expression. 1851 copy (bool): if `False`, modify this expression instance in-place. 1852 opts (kwargs): other options to use to parse the input expressions. 1853 1854 Returns: 1855 Select: the modified expression. 1856 """ 1857 alias_expression = maybe_parse( 1858 alias, 1859 dialect=dialect, 1860 into=TableAlias, 1861 **opts, 1862 ) 1863 as_expression = maybe_parse( 1864 as_, 1865 dialect=dialect, 1866 **opts, 1867 ) 1868 cte = CTE( 1869 this=as_expression, 1870 alias=alias_expression, 1871 ) 1872 return _apply_child_list_builder( 1873 cte, 1874 instance=self, 1875 arg="with", 1876 append=append, 1877 copy=copy, 1878 into=With, 1879 properties={"recursive": recursive or False}, 1880 )
1785 def subquery(self, alias=None, copy=True) -> Subquery: 1786 """ 1787 Convert this expression to an aliased expression that can be used as a Subquery. 1788 1789 Example: 1790 >>> subquery = Select().select("x").from_("tbl").subquery() 1791 >>> Select().select("x").from_(subquery).sql() 1792 'SELECT x FROM (SELECT x FROM tbl)' 1793 1794 Args: 1795 alias (str | Identifier): an optional alias for the subquery 1796 copy (bool): if `False`, modify this expression instance in-place. 1797 1798 Returns: 1799 Alias: the subquery 1800 """ 1801 instance = _maybe_copy(self, copy) 1802 return Subquery( 1803 this=instance, 1804 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1805 )
Convert this expression to an aliased expression that can be used as a Subquery.
Example:
>>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
- alias (str | Identifier): an optional alias for the subquery
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Alias: the subquery
1825 def with_( 1826 self, 1827 alias, 1828 as_, 1829 recursive=None, 1830 append=True, 1831 dialect=None, 1832 copy=True, 1833 **opts, 1834 ): 1835 """ 1836 Append to or set the common table expressions. 1837 1838 Example: 1839 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1840 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1841 1842 Args: 1843 alias (str | Expression): the SQL code string to parse as the table name. 1844 If an `Expression` instance is passed, this is used as-is. 1845 as_ (str | Expression): the SQL code string to parse as the table expression. 1846 If an `Expression` instance is passed, it will be used as-is. 1847 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1848 append (bool): if `True`, add to any existing expressions. 1849 Otherwise, this resets the expressions. 1850 dialect (str): the dialect used to parse the input expression. 1851 copy (bool): if `False`, modify this expression instance in-place. 1852 opts (kwargs): other options to use to parse the input expressions. 1853 1854 Returns: 1855 Select: the modified expression. 1856 """ 1857 alias_expression = maybe_parse( 1858 alias, 1859 dialect=dialect, 1860 into=TableAlias, 1861 **opts, 1862 ) 1863 as_expression = maybe_parse( 1864 as_, 1865 dialect=dialect, 1866 **opts, 1867 ) 1868 cte = CTE( 1869 this=as_expression, 1870 alias=alias_expression, 1871 ) 1872 return _apply_child_list_builder( 1873 cte, 1874 instance=self, 1875 arg="with", 1876 append=append, 1877 copy=copy, 1878 into=With, 1879 properties={"recursive": recursive or False}, 1880 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias (str | Expression): the SQL code string to parse as the table name.
If an
Expressioninstance is passed, this is used as-is. - as_ (str | Expression): the SQL code string to parse as the table expression.
If an
Expressioninstance is passed, it will be used as-is. - recursive (bool): set the RECURSIVE part of the expression. Defaults to
False. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1904class Table(Expression): 1905 arg_types = { 1906 "this": True, 1907 "alias": False, 1908 "db": False, 1909 "catalog": False, 1910 "laterals": False, 1911 "joins": False, 1912 "pivots": False, 1913 "hints": False, 1914 "system_time": False, 1915 } 1916 1917 @property 1918 def db(self) -> str: 1919 return self.text("db") 1920 1921 @property 1922 def catalog(self) -> str: 1923 return self.text("catalog")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1927class SystemTime(Expression): 1928 arg_types = { 1929 "this": False, 1930 "expression": False, 1931 "kind": True, 1932 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1935class Union(Subqueryable): 1936 arg_types = { 1937 "with": False, 1938 "this": True, 1939 "expression": True, 1940 "distinct": False, 1941 **QUERY_MODIFIERS, 1942 } 1943 1944 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1945 """ 1946 Set the LIMIT expression. 1947 1948 Example: 1949 >>> select("1").union(select("1")).limit(1).sql() 1950 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1951 1952 Args: 1953 expression (str | int | Expression): the SQL code string to parse. 1954 This can also be an integer. 1955 If a `Limit` instance is passed, this is used as-is. 1956 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1957 dialect (str): the dialect used to parse the input expression. 1958 copy (bool): if `False`, modify this expression instance in-place. 1959 opts (kwargs): other options to use to parse the input expressions. 1960 1961 Returns: 1962 Select: The limited subqueryable. 1963 """ 1964 return ( 1965 select("*") 1966 .from_(self.subquery(alias="_l_0", copy=copy)) 1967 .limit(expression, dialect=dialect, copy=False, **opts) 1968 ) 1969 1970 def select( 1971 self, 1972 *expressions: ExpOrStr, 1973 append: bool = True, 1974 dialect: DialectType = None, 1975 copy: bool = True, 1976 **opts, 1977 ) -> Union: 1978 """Append to or set the SELECT of the union recursively. 1979 1980 Example: 1981 >>> from sqlglot import parse_one 1982 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1983 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1984 1985 Args: 1986 *expressions: the SQL code strings to parse. 1987 If an `Expression` instance is passed, it will be used as-is. 1988 append: if `True`, add to any existing expressions. 1989 Otherwise, this resets the expressions. 1990 dialect: the dialect used to parse the input expressions. 1991 copy: if `False`, modify this expression instance in-place. 1992 opts: other options to use to parse the input expressions. 1993 1994 Returns: 1995 Union: the modified expression. 1996 """ 1997 this = self.copy() if copy else self 1998 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1999 this.expression.unnest().select( 2000 *expressions, append=append, dialect=dialect, copy=False, **opts 2001 ) 2002 return this 2003 2004 @property 2005 def named_selects(self): 2006 return self.this.unnest().named_selects 2007 2008 @property 2009 def is_star(self) -> bool: 2010 return self.this.is_star or self.expression.is_star 2011 2012 @property 2013 def selects(self): 2014 return self.this.unnest().selects 2015 2016 @property 2017 def left(self): 2018 return self.this 2019 2020 @property 2021 def right(self): 2022 return self.expression
1944 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1945 """ 1946 Set the LIMIT expression. 1947 1948 Example: 1949 >>> select("1").union(select("1")).limit(1).sql() 1950 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1951 1952 Args: 1953 expression (str | int | Expression): the SQL code string to parse. 1954 This can also be an integer. 1955 If a `Limit` instance is passed, this is used as-is. 1956 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1957 dialect (str): the dialect used to parse the input expression. 1958 copy (bool): if `False`, modify this expression instance in-place. 1959 opts (kwargs): other options to use to parse the input expressions. 1960 1961 Returns: 1962 Select: The limited subqueryable. 1963 """ 1964 return ( 1965 select("*") 1966 .from_(self.subquery(alias="_l_0", copy=copy)) 1967 .limit(expression, dialect=dialect, copy=False, **opts) 1968 )
Set the LIMIT expression.
Example:
>>> select("1").union(select("1")).limit(1).sql() 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: The limited subqueryable.
1970 def select( 1971 self, 1972 *expressions: ExpOrStr, 1973 append: bool = True, 1974 dialect: DialectType = None, 1975 copy: bool = True, 1976 **opts, 1977 ) -> Union: 1978 """Append to or set the SELECT of the union recursively. 1979 1980 Example: 1981 >>> from sqlglot import parse_one 1982 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 1983 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 1984 1985 Args: 1986 *expressions: the SQL code strings to parse. 1987 If an `Expression` instance is passed, it will be used as-is. 1988 append: if `True`, add to any existing expressions. 1989 Otherwise, this resets the expressions. 1990 dialect: the dialect used to parse the input expressions. 1991 copy: if `False`, modify this expression instance in-place. 1992 opts: other options to use to parse the input expressions. 1993 1994 Returns: 1995 Union: the modified expression. 1996 """ 1997 this = self.copy() if copy else self 1998 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 1999 this.expression.unnest().select( 2000 *expressions, append=append, dialect=dialect, copy=False, **opts 2001 ) 2002 return this
Append to or set the SELECT of the union recursively.
Example:
>>> from sqlglot import parse_one >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Union: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2033class Unnest(UDTF): 2034 arg_types = { 2035 "expressions": True, 2036 "ordinality": False, 2037 "alias": False, 2038 "offset": False, 2039 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2042class Update(Expression): 2043 arg_types = { 2044 "with": False, 2045 "this": False, 2046 "expressions": True, 2047 "from": False, 2048 "where": False, 2049 "returning": False, 2050 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2053class Values(UDTF): 2054 arg_types = { 2055 "expressions": True, 2056 "ordinality": False, 2057 "alias": False, 2058 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2075class Select(Subqueryable): 2076 arg_types = { 2077 "with": False, 2078 "kind": False, 2079 "expressions": False, 2080 "hint": False, 2081 "distinct": False, 2082 "into": False, 2083 "from": False, 2084 **QUERY_MODIFIERS, 2085 } 2086 2087 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2088 """ 2089 Set the FROM expression. 2090 2091 Example: 2092 >>> Select().from_("tbl").select("x").sql() 2093 'SELECT x FROM tbl' 2094 2095 Args: 2096 *expressions (str | Expression): the SQL code strings to parse. 2097 If a `From` instance is passed, this is used as-is. 2098 If another `Expression` instance is passed, it will be wrapped in a `From`. 2099 append (bool): if `True`, add to any existing expressions. 2100 Otherwise, this flattens all the `From` expression into a single expression. 2101 dialect (str): the dialect used to parse the input expression. 2102 copy (bool): if `False`, modify this expression instance in-place. 2103 opts (kwargs): other options to use to parse the input expressions. 2104 2105 Returns: 2106 Select: the modified expression. 2107 """ 2108 return _apply_child_list_builder( 2109 *expressions, 2110 instance=self, 2111 arg="from", 2112 append=append, 2113 copy=copy, 2114 prefix="FROM", 2115 into=From, 2116 dialect=dialect, 2117 **opts, 2118 ) 2119 2120 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2121 """ 2122 Set the GROUP BY expression. 2123 2124 Example: 2125 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2126 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2127 2128 Args: 2129 *expressions (str | Expression): the SQL code strings to parse. 2130 If a `Group` instance is passed, this is used as-is. 2131 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2132 If nothing is passed in then a group by is not applied to the expression 2133 append (bool): if `True`, add to any existing expressions. 2134 Otherwise, this flattens all the `Group` expression into a single expression. 2135 dialect (str): the dialect used to parse the input expression. 2136 copy (bool): if `False`, modify this expression instance in-place. 2137 opts (kwargs): other options to use to parse the input expressions. 2138 2139 Returns: 2140 Select: the modified expression. 2141 """ 2142 if not expressions: 2143 return self if not copy else self.copy() 2144 return _apply_child_list_builder( 2145 *expressions, 2146 instance=self, 2147 arg="group", 2148 append=append, 2149 copy=copy, 2150 prefix="GROUP BY", 2151 into=Group, 2152 dialect=dialect, 2153 **opts, 2154 ) 2155 2156 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2157 """ 2158 Set the ORDER BY expression. 2159 2160 Example: 2161 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2162 'SELECT x FROM tbl ORDER BY x DESC' 2163 2164 Args: 2165 *expressions (str | Expression): the SQL code strings to parse. 2166 If a `Group` instance is passed, this is used as-is. 2167 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2168 append (bool): if `True`, add to any existing expressions. 2169 Otherwise, this flattens all the `Order` expression into a single expression. 2170 dialect (str): the dialect used to parse the input expression. 2171 copy (bool): if `False`, modify this expression instance in-place. 2172 opts (kwargs): other options to use to parse the input expressions. 2173 2174 Returns: 2175 Select: the modified expression. 2176 """ 2177 return _apply_child_list_builder( 2178 *expressions, 2179 instance=self, 2180 arg="order", 2181 append=append, 2182 copy=copy, 2183 prefix="ORDER BY", 2184 into=Order, 2185 dialect=dialect, 2186 **opts, 2187 ) 2188 2189 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2190 """ 2191 Set the SORT BY expression. 2192 2193 Example: 2194 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2195 'SELECT x FROM tbl SORT BY x DESC' 2196 2197 Args: 2198 *expressions (str | Expression): the SQL code strings to parse. 2199 If a `Group` instance is passed, this is used as-is. 2200 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2201 append (bool): if `True`, add to any existing expressions. 2202 Otherwise, this flattens all the `Order` expression into a single expression. 2203 dialect (str): the dialect used to parse the input expression. 2204 copy (bool): if `False`, modify this expression instance in-place. 2205 opts (kwargs): other options to use to parse the input expressions. 2206 2207 Returns: 2208 Select: the modified expression. 2209 """ 2210 return _apply_child_list_builder( 2211 *expressions, 2212 instance=self, 2213 arg="sort", 2214 append=append, 2215 copy=copy, 2216 prefix="SORT BY", 2217 into=Sort, 2218 dialect=dialect, 2219 **opts, 2220 ) 2221 2222 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2223 """ 2224 Set the CLUSTER BY expression. 2225 2226 Example: 2227 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2228 'SELECT x FROM tbl CLUSTER BY x DESC' 2229 2230 Args: 2231 *expressions (str | Expression): the SQL code strings to parse. 2232 If a `Group` instance is passed, this is used as-is. 2233 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2234 append (bool): if `True`, add to any existing expressions. 2235 Otherwise, this flattens all the `Order` expression into a single expression. 2236 dialect (str): the dialect used to parse the input expression. 2237 copy (bool): if `False`, modify this expression instance in-place. 2238 opts (kwargs): other options to use to parse the input expressions. 2239 2240 Returns: 2241 Select: the modified expression. 2242 """ 2243 return _apply_child_list_builder( 2244 *expressions, 2245 instance=self, 2246 arg="cluster", 2247 append=append, 2248 copy=copy, 2249 prefix="CLUSTER BY", 2250 into=Cluster, 2251 dialect=dialect, 2252 **opts, 2253 ) 2254 2255 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2256 """ 2257 Set the LIMIT expression. 2258 2259 Example: 2260 >>> Select().from_("tbl").select("x").limit(10).sql() 2261 'SELECT x FROM tbl LIMIT 10' 2262 2263 Args: 2264 expression (str | int | Expression): the SQL code string to parse. 2265 This can also be an integer. 2266 If a `Limit` instance is passed, this is used as-is. 2267 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2268 dialect (str): the dialect used to parse the input expression. 2269 copy (bool): if `False`, modify this expression instance in-place. 2270 opts (kwargs): other options to use to parse the input expressions. 2271 2272 Returns: 2273 Select: the modified expression. 2274 """ 2275 return _apply_builder( 2276 expression=expression, 2277 instance=self, 2278 arg="limit", 2279 into=Limit, 2280 prefix="LIMIT", 2281 dialect=dialect, 2282 copy=copy, 2283 **opts, 2284 ) 2285 2286 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2287 """ 2288 Set the OFFSET expression. 2289 2290 Example: 2291 >>> Select().from_("tbl").select("x").offset(10).sql() 2292 'SELECT x FROM tbl OFFSET 10' 2293 2294 Args: 2295 expression (str | int | Expression): the SQL code string to parse. 2296 This can also be an integer. 2297 If a `Offset` instance is passed, this is used as-is. 2298 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2299 dialect (str): the dialect used to parse the input expression. 2300 copy (bool): if `False`, modify this expression instance in-place. 2301 opts (kwargs): other options to use to parse the input expressions. 2302 2303 Returns: 2304 Select: the modified expression. 2305 """ 2306 return _apply_builder( 2307 expression=expression, 2308 instance=self, 2309 arg="offset", 2310 into=Offset, 2311 prefix="OFFSET", 2312 dialect=dialect, 2313 copy=copy, 2314 **opts, 2315 ) 2316 2317 def select( 2318 self, 2319 *expressions: ExpOrStr, 2320 append: bool = True, 2321 dialect: DialectType = None, 2322 copy: bool = True, 2323 **opts, 2324 ) -> Select: 2325 """ 2326 Append to or set the SELECT expressions. 2327 2328 Example: 2329 >>> Select().select("x", "y").sql() 2330 'SELECT x, y' 2331 2332 Args: 2333 *expressions: the SQL code strings to parse. 2334 If an `Expression` instance is passed, it will be used as-is. 2335 append: if `True`, add to any existing expressions. 2336 Otherwise, this resets the expressions. 2337 dialect: the dialect used to parse the input expressions. 2338 copy: if `False`, modify this expression instance in-place. 2339 opts: other options to use to parse the input expressions. 2340 2341 Returns: 2342 Select: the modified expression. 2343 """ 2344 return _apply_list_builder( 2345 *expressions, 2346 instance=self, 2347 arg="expressions", 2348 append=append, 2349 dialect=dialect, 2350 copy=copy, 2351 **opts, 2352 ) 2353 2354 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2355 """ 2356 Append to or set the LATERAL expressions. 2357 2358 Example: 2359 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2360 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2361 2362 Args: 2363 *expressions (str | Expression): the SQL code strings to parse. 2364 If an `Expression` instance is passed, it will be used as-is. 2365 append (bool): if `True`, add to any existing expressions. 2366 Otherwise, this resets the expressions. 2367 dialect (str): the dialect used to parse the input expressions. 2368 copy (bool): if `False`, modify this expression instance in-place. 2369 opts (kwargs): other options to use to parse the input expressions. 2370 2371 Returns: 2372 Select: the modified expression. 2373 """ 2374 return _apply_list_builder( 2375 *expressions, 2376 instance=self, 2377 arg="laterals", 2378 append=append, 2379 into=Lateral, 2380 prefix="LATERAL VIEW", 2381 dialect=dialect, 2382 copy=copy, 2383 **opts, 2384 ) 2385 2386 def join( 2387 self, 2388 expression, 2389 on=None, 2390 using=None, 2391 append=True, 2392 join_type=None, 2393 join_alias=None, 2394 dialect=None, 2395 copy=True, 2396 **opts, 2397 ) -> Select: 2398 """ 2399 Append to or set the JOIN expressions. 2400 2401 Example: 2402 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2403 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2404 2405 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2406 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2407 2408 Use `join_type` to change the type of join: 2409 2410 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2411 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2412 2413 Args: 2414 expression (str | Expression): the SQL code string to parse. 2415 If an `Expression` instance is passed, it will be used as-is. 2416 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2417 If an `Expression` instance is passed, it will be used as-is. 2418 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2419 If an `Expression` instance is passed, it will be used as-is. 2420 append (bool): if `True`, add to any existing expressions. 2421 Otherwise, this resets the expressions. 2422 join_type (str): If set, alter the parsed join type 2423 dialect (str): the dialect used to parse the input expressions. 2424 copy (bool): if `False`, modify this expression instance in-place. 2425 opts (kwargs): other options to use to parse the input expressions. 2426 2427 Returns: 2428 Select: the modified expression. 2429 """ 2430 parse_args = {"dialect": dialect, **opts} 2431 2432 try: 2433 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2434 except ParseError: 2435 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2436 2437 join = expression if isinstance(expression, Join) else Join(this=expression) 2438 2439 if isinstance(join.this, Select): 2440 join.this.replace(join.this.subquery()) 2441 2442 if join_type: 2443 natural: t.Optional[Token] 2444 side: t.Optional[Token] 2445 kind: t.Optional[Token] 2446 2447 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2448 2449 if natural: 2450 join.set("natural", True) 2451 if side: 2452 join.set("side", side.text) 2453 if kind: 2454 join.set("kind", kind.text) 2455 2456 if on: 2457 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2458 join.set("on", on) 2459 2460 if using: 2461 join = _apply_list_builder( 2462 *ensure_collection(using), 2463 instance=join, 2464 arg="using", 2465 append=append, 2466 copy=copy, 2467 **opts, 2468 ) 2469 2470 if join_alias: 2471 join.set("this", alias_(join.this, join_alias, table=True)) 2472 return _apply_list_builder( 2473 join, 2474 instance=self, 2475 arg="joins", 2476 append=append, 2477 copy=copy, 2478 **opts, 2479 ) 2480 2481 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2482 """ 2483 Append to or set the WHERE expressions. 2484 2485 Example: 2486 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2487 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2488 2489 Args: 2490 *expressions (str | Expression): the SQL code strings to parse. 2491 If an `Expression` instance is passed, it will be used as-is. 2492 Multiple expressions are combined with an AND operator. 2493 append (bool): if `True`, AND the new expressions to any existing expression. 2494 Otherwise, this resets the expression. 2495 dialect (str): the dialect used to parse the input expressions. 2496 copy (bool): if `False`, modify this expression instance in-place. 2497 opts (kwargs): other options to use to parse the input expressions. 2498 2499 Returns: 2500 Select: the modified expression. 2501 """ 2502 return _apply_conjunction_builder( 2503 *expressions, 2504 instance=self, 2505 arg="where", 2506 append=append, 2507 into=Where, 2508 dialect=dialect, 2509 copy=copy, 2510 **opts, 2511 ) 2512 2513 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2514 """ 2515 Append to or set the HAVING expressions. 2516 2517 Example: 2518 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2519 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2520 2521 Args: 2522 *expressions (str | Expression): the SQL code strings to parse. 2523 If an `Expression` instance is passed, it will be used as-is. 2524 Multiple expressions are combined with an AND operator. 2525 append (bool): if `True`, AND the new expressions to any existing expression. 2526 Otherwise, this resets the expression. 2527 dialect (str): the dialect used to parse the input expressions. 2528 copy (bool): if `False`, modify this expression instance in-place. 2529 opts (kwargs): other options to use to parse the input expressions. 2530 2531 Returns: 2532 Select: the modified expression. 2533 """ 2534 return _apply_conjunction_builder( 2535 *expressions, 2536 instance=self, 2537 arg="having", 2538 append=append, 2539 into=Having, 2540 dialect=dialect, 2541 copy=copy, 2542 **opts, 2543 ) 2544 2545 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2546 return _apply_list_builder( 2547 *expressions, 2548 instance=self, 2549 arg="windows", 2550 append=append, 2551 into=Window, 2552 dialect=dialect, 2553 copy=copy, 2554 **opts, 2555 ) 2556 2557 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2558 return _apply_conjunction_builder( 2559 *expressions, 2560 instance=self, 2561 arg="qualify", 2562 append=append, 2563 into=Qualify, 2564 dialect=dialect, 2565 copy=copy, 2566 **opts, 2567 ) 2568 2569 def distinct(self, distinct=True, copy=True) -> Select: 2570 """ 2571 Set the OFFSET expression. 2572 2573 Example: 2574 >>> Select().from_("tbl").select("x").distinct().sql() 2575 'SELECT DISTINCT x FROM tbl' 2576 2577 Args: 2578 distinct (bool): whether the Select should be distinct 2579 copy (bool): if `False`, modify this expression instance in-place. 2580 2581 Returns: 2582 Select: the modified expression. 2583 """ 2584 instance = _maybe_copy(self, copy) 2585 instance.set("distinct", Distinct() if distinct else None) 2586 return instance 2587 2588 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2589 """ 2590 Convert this expression to a CREATE TABLE AS statement. 2591 2592 Example: 2593 >>> Select().select("*").from_("tbl").ctas("x").sql() 2594 'CREATE TABLE x AS SELECT * FROM tbl' 2595 2596 Args: 2597 table (str | Expression): the SQL code string to parse as the table name. 2598 If another `Expression` instance is passed, it will be used as-is. 2599 properties (dict): an optional mapping of table properties 2600 dialect (str): the dialect used to parse the input table. 2601 copy (bool): if `False`, modify this expression instance in-place. 2602 opts (kwargs): other options to use to parse the input table. 2603 2604 Returns: 2605 Create: the CREATE TABLE AS expression 2606 """ 2607 instance = _maybe_copy(self, copy) 2608 table_expression = maybe_parse( 2609 table, 2610 into=Table, 2611 dialect=dialect, 2612 **opts, 2613 ) 2614 properties_expression = None 2615 if properties: 2616 properties_expression = Properties.from_dict(properties) 2617 2618 return Create( 2619 this=table_expression, 2620 kind="table", 2621 expression=instance, 2622 properties=properties_expression, 2623 ) 2624 2625 def lock(self, update: bool = True, copy: bool = True) -> Select: 2626 """ 2627 Set the locking read mode for this expression. 2628 2629 Examples: 2630 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2631 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2632 2633 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2634 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2635 2636 Args: 2637 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2638 copy: if `False`, modify this expression instance in-place. 2639 2640 Returns: 2641 The modified expression. 2642 """ 2643 2644 inst = _maybe_copy(self, copy) 2645 inst.set("lock", Lock(update=update)) 2646 2647 return inst 2648 2649 @property 2650 def named_selects(self) -> t.List[str]: 2651 return [e.output_name for e in self.expressions if e.alias_or_name] 2652 2653 @property 2654 def is_star(self) -> bool: 2655 return any(expression.is_star for expression in self.expressions) 2656 2657 @property 2658 def selects(self) -> t.List[Expression]: 2659 return self.expressions
2087 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2088 """ 2089 Set the FROM expression. 2090 2091 Example: 2092 >>> Select().from_("tbl").select("x").sql() 2093 'SELECT x FROM tbl' 2094 2095 Args: 2096 *expressions (str | Expression): the SQL code strings to parse. 2097 If a `From` instance is passed, this is used as-is. 2098 If another `Expression` instance is passed, it will be wrapped in a `From`. 2099 append (bool): if `True`, add to any existing expressions. 2100 Otherwise, this flattens all the `From` expression into a single expression. 2101 dialect (str): the dialect used to parse the input expression. 2102 copy (bool): if `False`, modify this expression instance in-place. 2103 opts (kwargs): other options to use to parse the input expressions. 2104 2105 Returns: 2106 Select: the modified expression. 2107 """ 2108 return _apply_child_list_builder( 2109 *expressions, 2110 instance=self, 2111 arg="from", 2112 append=append, 2113 copy=copy, 2114 prefix="FROM", 2115 into=From, 2116 dialect=dialect, 2117 **opts, 2118 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Frominstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aFrom. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theFromexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2120 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2121 """ 2122 Set the GROUP BY expression. 2123 2124 Example: 2125 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2126 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2127 2128 Args: 2129 *expressions (str | Expression): the SQL code strings to parse. 2130 If a `Group` instance is passed, this is used as-is. 2131 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2132 If nothing is passed in then a group by is not applied to the expression 2133 append (bool): if `True`, add to any existing expressions. 2134 Otherwise, this flattens all the `Group` expression into a single expression. 2135 dialect (str): the dialect used to parse the input expression. 2136 copy (bool): if `False`, modify this expression instance in-place. 2137 opts (kwargs): other options to use to parse the input expressions. 2138 2139 Returns: 2140 Select: the modified expression. 2141 """ 2142 if not expressions: 2143 return self if not copy else self.copy() 2144 return _apply_child_list_builder( 2145 *expressions, 2146 instance=self, 2147 arg="group", 2148 append=append, 2149 copy=copy, 2150 prefix="GROUP BY", 2151 into=Group, 2152 dialect=dialect, 2153 **opts, 2154 )
Set the GROUP BY expression.
Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aGroup. If nothing is passed in then a group by is not applied to the expression - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theGroupexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2156 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2157 """ 2158 Set the ORDER BY expression. 2159 2160 Example: 2161 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2162 'SELECT x FROM tbl ORDER BY x DESC' 2163 2164 Args: 2165 *expressions (str | Expression): the SQL code strings to parse. 2166 If a `Group` instance is passed, this is used as-is. 2167 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2168 append (bool): if `True`, add to any existing expressions. 2169 Otherwise, this flattens all the `Order` expression into a single expression. 2170 dialect (str): the dialect used to parse the input expression. 2171 copy (bool): if `False`, modify this expression instance in-place. 2172 opts (kwargs): other options to use to parse the input expressions. 2173 2174 Returns: 2175 Select: the modified expression. 2176 """ 2177 return _apply_child_list_builder( 2178 *expressions, 2179 instance=self, 2180 arg="order", 2181 append=append, 2182 copy=copy, 2183 prefix="ORDER BY", 2184 into=Order, 2185 dialect=dialect, 2186 **opts, 2187 )
Set the ORDER BY expression.
Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOrder. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2189 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2190 """ 2191 Set the SORT BY expression. 2192 2193 Example: 2194 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2195 'SELECT x FROM tbl SORT BY x DESC' 2196 2197 Args: 2198 *expressions (str | Expression): the SQL code strings to parse. 2199 If a `Group` instance is passed, this is used as-is. 2200 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2201 append (bool): if `True`, add to any existing expressions. 2202 Otherwise, this flattens all the `Order` expression into a single expression. 2203 dialect (str): the dialect used to parse the input expression. 2204 copy (bool): if `False`, modify this expression instance in-place. 2205 opts (kwargs): other options to use to parse the input expressions. 2206 2207 Returns: 2208 Select: the modified expression. 2209 """ 2210 return _apply_child_list_builder( 2211 *expressions, 2212 instance=self, 2213 arg="sort", 2214 append=append, 2215 copy=copy, 2216 prefix="SORT BY", 2217 into=Sort, 2218 dialect=dialect, 2219 **opts, 2220 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aSORT. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2222 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2223 """ 2224 Set the CLUSTER BY expression. 2225 2226 Example: 2227 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2228 'SELECT x FROM tbl CLUSTER BY x DESC' 2229 2230 Args: 2231 *expressions (str | Expression): the SQL code strings to parse. 2232 If a `Group` instance is passed, this is used as-is. 2233 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2234 append (bool): if `True`, add to any existing expressions. 2235 Otherwise, this flattens all the `Order` expression into a single expression. 2236 dialect (str): the dialect used to parse the input expression. 2237 copy (bool): if `False`, modify this expression instance in-place. 2238 opts (kwargs): other options to use to parse the input expressions. 2239 2240 Returns: 2241 Select: the modified expression. 2242 """ 2243 return _apply_child_list_builder( 2244 *expressions, 2245 instance=self, 2246 arg="cluster", 2247 append=append, 2248 copy=copy, 2249 prefix="CLUSTER BY", 2250 into=Cluster, 2251 dialect=dialect, 2252 **opts, 2253 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aCluster. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2255 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2256 """ 2257 Set the LIMIT expression. 2258 2259 Example: 2260 >>> Select().from_("tbl").select("x").limit(10).sql() 2261 'SELECT x FROM tbl LIMIT 10' 2262 2263 Args: 2264 expression (str | int | Expression): the SQL code string to parse. 2265 This can also be an integer. 2266 If a `Limit` instance is passed, this is used as-is. 2267 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2268 dialect (str): the dialect used to parse the input expression. 2269 copy (bool): if `False`, modify this expression instance in-place. 2270 opts (kwargs): other options to use to parse the input expressions. 2271 2272 Returns: 2273 Select: the modified expression. 2274 """ 2275 return _apply_builder( 2276 expression=expression, 2277 instance=self, 2278 arg="limit", 2279 into=Limit, 2280 prefix="LIMIT", 2281 dialect=dialect, 2282 copy=copy, 2283 **opts, 2284 )
Set the LIMIT expression.
Example:
>>> Select().from_("tbl").select("x").limit(10).sql() 'SELECT x FROM tbl LIMIT 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2286 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2287 """ 2288 Set the OFFSET expression. 2289 2290 Example: 2291 >>> Select().from_("tbl").select("x").offset(10).sql() 2292 'SELECT x FROM tbl OFFSET 10' 2293 2294 Args: 2295 expression (str | int | Expression): the SQL code string to parse. 2296 This can also be an integer. 2297 If a `Offset` instance is passed, this is used as-is. 2298 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2299 dialect (str): the dialect used to parse the input expression. 2300 copy (bool): if `False`, modify this expression instance in-place. 2301 opts (kwargs): other options to use to parse the input expressions. 2302 2303 Returns: 2304 Select: the modified expression. 2305 """ 2306 return _apply_builder( 2307 expression=expression, 2308 instance=self, 2309 arg="offset", 2310 into=Offset, 2311 prefix="OFFSET", 2312 dialect=dialect, 2313 copy=copy, 2314 **opts, 2315 )
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Offsetinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOffset. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2317 def select( 2318 self, 2319 *expressions: ExpOrStr, 2320 append: bool = True, 2321 dialect: DialectType = None, 2322 copy: bool = True, 2323 **opts, 2324 ) -> Select: 2325 """ 2326 Append to or set the SELECT expressions. 2327 2328 Example: 2329 >>> Select().select("x", "y").sql() 2330 'SELECT x, y' 2331 2332 Args: 2333 *expressions: the SQL code strings to parse. 2334 If an `Expression` instance is passed, it will be used as-is. 2335 append: if `True`, add to any existing expressions. 2336 Otherwise, this resets the expressions. 2337 dialect: the dialect used to parse the input expressions. 2338 copy: if `False`, modify this expression instance in-place. 2339 opts: other options to use to parse the input expressions. 2340 2341 Returns: 2342 Select: the modified expression. 2343 """ 2344 return _apply_list_builder( 2345 *expressions, 2346 instance=self, 2347 arg="expressions", 2348 append=append, 2349 dialect=dialect, 2350 copy=copy, 2351 **opts, 2352 )
Append to or set the SELECT expressions.
Example:
>>> Select().select("x", "y").sql() 'SELECT x, y'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2354 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2355 """ 2356 Append to or set the LATERAL expressions. 2357 2358 Example: 2359 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2360 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2361 2362 Args: 2363 *expressions (str | Expression): the SQL code strings to parse. 2364 If an `Expression` instance is passed, it will be used as-is. 2365 append (bool): if `True`, add to any existing expressions. 2366 Otherwise, this resets the expressions. 2367 dialect (str): the dialect used to parse the input expressions. 2368 copy (bool): if `False`, modify this expression instance in-place. 2369 opts (kwargs): other options to use to parse the input expressions. 2370 2371 Returns: 2372 Select: the modified expression. 2373 """ 2374 return _apply_list_builder( 2375 *expressions, 2376 instance=self, 2377 arg="laterals", 2378 append=append, 2379 into=Lateral, 2380 prefix="LATERAL VIEW", 2381 dialect=dialect, 2382 copy=copy, 2383 **opts, 2384 )
Append to or set the LATERAL expressions.
Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2386 def join( 2387 self, 2388 expression, 2389 on=None, 2390 using=None, 2391 append=True, 2392 join_type=None, 2393 join_alias=None, 2394 dialect=None, 2395 copy=True, 2396 **opts, 2397 ) -> Select: 2398 """ 2399 Append to or set the JOIN expressions. 2400 2401 Example: 2402 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2403 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2404 2405 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2406 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2407 2408 Use `join_type` to change the type of join: 2409 2410 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2411 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2412 2413 Args: 2414 expression (str | Expression): the SQL code string to parse. 2415 If an `Expression` instance is passed, it will be used as-is. 2416 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2417 If an `Expression` instance is passed, it will be used as-is. 2418 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2419 If an `Expression` instance is passed, it will be used as-is. 2420 append (bool): if `True`, add to any existing expressions. 2421 Otherwise, this resets the expressions. 2422 join_type (str): If set, alter the parsed join type 2423 dialect (str): the dialect used to parse the input expressions. 2424 copy (bool): if `False`, modify this expression instance in-place. 2425 opts (kwargs): other options to use to parse the input expressions. 2426 2427 Returns: 2428 Select: the modified expression. 2429 """ 2430 parse_args = {"dialect": dialect, **opts} 2431 2432 try: 2433 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2434 except ParseError: 2435 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2436 2437 join = expression if isinstance(expression, Join) else Join(this=expression) 2438 2439 if isinstance(join.this, Select): 2440 join.this.replace(join.this.subquery()) 2441 2442 if join_type: 2443 natural: t.Optional[Token] 2444 side: t.Optional[Token] 2445 kind: t.Optional[Token] 2446 2447 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2448 2449 if natural: 2450 join.set("natural", True) 2451 if side: 2452 join.set("side", side.text) 2453 if kind: 2454 join.set("kind", kind.text) 2455 2456 if on: 2457 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2458 join.set("on", on) 2459 2460 if using: 2461 join = _apply_list_builder( 2462 *ensure_collection(using), 2463 instance=join, 2464 arg="using", 2465 append=append, 2466 copy=copy, 2467 **opts, 2468 ) 2469 2470 if join_alias: 2471 join.set("this", alias_(join.this, join_alias, table=True)) 2472 return _apply_list_builder( 2473 join, 2474 instance=self, 2475 arg="joins", 2476 append=append, 2477 copy=copy, 2478 **opts, 2479 )
Append to or set the JOIN expressions.
Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'Use
join_typeto change the type of join:>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
- expression (str | Expression): the SQL code string to parse.
If an
Expressioninstance is passed, it will be used as-is. - on (str | Expression): optionally specify the join "on" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - using (str | Expression): optionally specify the join "using" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - join_type (str): If set, alter the parsed join type
- dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2481 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2482 """ 2483 Append to or set the WHERE expressions. 2484 2485 Example: 2486 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2487 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2488 2489 Args: 2490 *expressions (str | Expression): the SQL code strings to parse. 2491 If an `Expression` instance is passed, it will be used as-is. 2492 Multiple expressions are combined with an AND operator. 2493 append (bool): if `True`, AND the new expressions to any existing expression. 2494 Otherwise, this resets the expression. 2495 dialect (str): the dialect used to parse the input expressions. 2496 copy (bool): if `False`, modify this expression instance in-place. 2497 opts (kwargs): other options to use to parse the input expressions. 2498 2499 Returns: 2500 Select: the modified expression. 2501 """ 2502 return _apply_conjunction_builder( 2503 *expressions, 2504 instance=self, 2505 arg="where", 2506 append=append, 2507 into=Where, 2508 dialect=dialect, 2509 copy=copy, 2510 **opts, 2511 )
Append to or set the WHERE expressions.
Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2513 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2514 """ 2515 Append to or set the HAVING expressions. 2516 2517 Example: 2518 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2519 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2520 2521 Args: 2522 *expressions (str | Expression): the SQL code strings to parse. 2523 If an `Expression` instance is passed, it will be used as-is. 2524 Multiple expressions are combined with an AND operator. 2525 append (bool): if `True`, AND the new expressions to any existing expression. 2526 Otherwise, this resets the expression. 2527 dialect (str): the dialect used to parse the input expressions. 2528 copy (bool): if `False`, modify this expression instance in-place. 2529 opts (kwargs): other options to use to parse the input expressions. 2530 2531 Returns: 2532 Select: the modified expression. 2533 """ 2534 return _apply_conjunction_builder( 2535 *expressions, 2536 instance=self, 2537 arg="having", 2538 append=append, 2539 into=Having, 2540 dialect=dialect, 2541 copy=copy, 2542 **opts, 2543 )
Append to or set the HAVING expressions.
Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2569 def distinct(self, distinct=True, copy=True) -> Select: 2570 """ 2571 Set the OFFSET expression. 2572 2573 Example: 2574 >>> Select().from_("tbl").select("x").distinct().sql() 2575 'SELECT DISTINCT x FROM tbl' 2576 2577 Args: 2578 distinct (bool): whether the Select should be distinct 2579 copy (bool): if `False`, modify this expression instance in-place. 2580 2581 Returns: 2582 Select: the modified expression. 2583 """ 2584 instance = _maybe_copy(self, copy) 2585 instance.set("distinct", Distinct() if distinct else None) 2586 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- distinct (bool): whether the Select should be distinct
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Select: the modified expression.
2588 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2589 """ 2590 Convert this expression to a CREATE TABLE AS statement. 2591 2592 Example: 2593 >>> Select().select("*").from_("tbl").ctas("x").sql() 2594 'CREATE TABLE x AS SELECT * FROM tbl' 2595 2596 Args: 2597 table (str | Expression): the SQL code string to parse as the table name. 2598 If another `Expression` instance is passed, it will be used as-is. 2599 properties (dict): an optional mapping of table properties 2600 dialect (str): the dialect used to parse the input table. 2601 copy (bool): if `False`, modify this expression instance in-place. 2602 opts (kwargs): other options to use to parse the input table. 2603 2604 Returns: 2605 Create: the CREATE TABLE AS expression 2606 """ 2607 instance = _maybe_copy(self, copy) 2608 table_expression = maybe_parse( 2609 table, 2610 into=Table, 2611 dialect=dialect, 2612 **opts, 2613 ) 2614 properties_expression = None 2615 if properties: 2616 properties_expression = Properties.from_dict(properties) 2617 2618 return Create( 2619 this=table_expression, 2620 kind="table", 2621 expression=instance, 2622 properties=properties_expression, 2623 )
Convert this expression to a CREATE TABLE AS statement.
Example:
>>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
- table (str | Expression): the SQL code string to parse as the table name.
If another
Expressioninstance is passed, it will be used as-is. - properties (dict): an optional mapping of table properties
- dialect (str): the dialect used to parse the input table.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input table.
Returns:
Create: the CREATE TABLE AS expression
2625 def lock(self, update: bool = True, copy: bool = True) -> Select: 2626 """ 2627 Set the locking read mode for this expression. 2628 2629 Examples: 2630 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2631 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2632 2633 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2634 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2635 2636 Args: 2637 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2638 copy: if `False`, modify this expression instance in-place. 2639 2640 Returns: 2641 The modified expression. 2642 """ 2643 2644 inst = _maybe_copy(self, copy) 2645 inst.set("lock", Lock(update=update)) 2646 2647 return inst
Set the locking read mode for this expression.
Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE">>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
- update: if
True, the locking type will beFOR UPDATE, else it will beFOR SHARE. - copy: if
False, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2662class Subquery(DerivedTable, Unionable): 2663 arg_types = { 2664 "this": True, 2665 "alias": False, 2666 "with": False, 2667 **QUERY_MODIFIERS, 2668 } 2669 2670 def unnest(self): 2671 """ 2672 Returns the first non subquery. 2673 """ 2674 expression = self 2675 while isinstance(expression, Subquery): 2676 expression = expression.this 2677 return expression 2678 2679 @property 2680 def is_star(self) -> bool: 2681 return self.this.is_star 2682 2683 @property 2684 def output_name(self): 2685 return self.alias
2670 def unnest(self): 2671 """ 2672 Returns the first non subquery. 2673 """ 2674 expression = self 2675 while isinstance(expression, Subquery): 2676 expression = expression.this 2677 return expression
Returns the first non subquery.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
2688class TableSample(Expression): 2689 arg_types = { 2690 "this": False, 2691 "method": False, 2692 "bucket_numerator": False, 2693 "bucket_denominator": False, 2694 "bucket_field": False, 2695 "percent": False, 2696 "rows": False, 2697 "size": False, 2698 "seed": False, 2699 "kind": False, 2700 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2703class Tag(Expression): 2704 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2705 2706 arg_types = { 2707 "this": False, 2708 "prefix": False, 2709 "postfix": False, 2710 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2713class Pivot(Expression): 2714 arg_types = { 2715 "this": False, 2716 "alias": False, 2717 "expressions": True, 2718 "field": True, 2719 "unpivot": True, 2720 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2723class Window(Expression): 2724 arg_types = { 2725 "this": True, 2726 "partition_by": False, 2727 "order": False, 2728 "spec": False, 2729 "alias": False, 2730 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2733class WindowSpec(Expression): 2734 arg_types = { 2735 "kind": False, 2736 "start": False, 2737 "start_side": False, 2738 "end": False, 2739 "end_side": False, 2740 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2747class Star(Expression): 2748 arg_types = {"except": False, "replace": False} 2749 2750 @property 2751 def name(self) -> str: 2752 return "*" 2753 2754 @property 2755 def output_name(self): 2756 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2771class Null(Condition): 2772 arg_types: t.Dict[str, t.Any] = {} 2773 2774 @property 2775 def name(self) -> str: 2776 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2783class DataType(Expression): 2784 arg_types = { 2785 "this": True, 2786 "expressions": False, 2787 "nested": False, 2788 "values": False, 2789 "prefix": False, 2790 } 2791 2792 class Type(AutoName): 2793 CHAR = auto() 2794 NCHAR = auto() 2795 VARCHAR = auto() 2796 NVARCHAR = auto() 2797 TEXT = auto() 2798 MEDIUMTEXT = auto() 2799 LONGTEXT = auto() 2800 MEDIUMBLOB = auto() 2801 LONGBLOB = auto() 2802 BINARY = auto() 2803 VARBINARY = auto() 2804 INT = auto() 2805 UINT = auto() 2806 TINYINT = auto() 2807 UTINYINT = auto() 2808 SMALLINT = auto() 2809 USMALLINT = auto() 2810 BIGINT = auto() 2811 UBIGINT = auto() 2812 FLOAT = auto() 2813 DOUBLE = auto() 2814 DECIMAL = auto() 2815 BIT = auto() 2816 BOOLEAN = auto() 2817 JSON = auto() 2818 JSONB = auto() 2819 INTERVAL = auto() 2820 TIME = auto() 2821 TIMESTAMP = auto() 2822 TIMESTAMPTZ = auto() 2823 TIMESTAMPLTZ = auto() 2824 DATE = auto() 2825 DATETIME = auto() 2826 ARRAY = auto() 2827 MAP = auto() 2828 UUID = auto() 2829 GEOGRAPHY = auto() 2830 GEOMETRY = auto() 2831 STRUCT = auto() 2832 NULLABLE = auto() 2833 HLLSKETCH = auto() 2834 HSTORE = auto() 2835 SUPER = auto() 2836 SERIAL = auto() 2837 SMALLSERIAL = auto() 2838 BIGSERIAL = auto() 2839 XML = auto() 2840 UNIQUEIDENTIFIER = auto() 2841 MONEY = auto() 2842 SMALLMONEY = auto() 2843 ROWVERSION = auto() 2844 IMAGE = auto() 2845 VARIANT = auto() 2846 OBJECT = auto() 2847 INET = auto() 2848 NULL = auto() 2849 UNKNOWN = auto() # Sentinel value, useful for type annotation 2850 2851 TEXT_TYPES = { 2852 Type.CHAR, 2853 Type.NCHAR, 2854 Type.VARCHAR, 2855 Type.NVARCHAR, 2856 Type.TEXT, 2857 } 2858 2859 INTEGER_TYPES = { 2860 Type.INT, 2861 Type.TINYINT, 2862 Type.SMALLINT, 2863 Type.BIGINT, 2864 } 2865 2866 FLOAT_TYPES = { 2867 Type.FLOAT, 2868 Type.DOUBLE, 2869 } 2870 2871 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2872 2873 TEMPORAL_TYPES = { 2874 Type.TIMESTAMP, 2875 Type.TIMESTAMPTZ, 2876 Type.TIMESTAMPLTZ, 2877 Type.DATE, 2878 Type.DATETIME, 2879 } 2880 2881 @classmethod 2882 def build( 2883 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2884 ) -> DataType: 2885 from sqlglot import parse_one 2886 2887 if isinstance(dtype, str): 2888 if dtype.upper() in cls.Type.__members__: 2889 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2890 else: 2891 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2892 if data_type_exp is None: 2893 raise ValueError(f"Unparsable data type value: {dtype}") 2894 elif isinstance(dtype, DataType.Type): 2895 data_type_exp = DataType(this=dtype) 2896 elif isinstance(dtype, DataType): 2897 return dtype 2898 else: 2899 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2900 return DataType(**{**data_type_exp.args, **kwargs}) 2901 2902 def is_type(self, dtype: DataType.Type) -> bool: 2903 return self.this == dtype
2881 @classmethod 2882 def build( 2883 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2884 ) -> DataType: 2885 from sqlglot import parse_one 2886 2887 if isinstance(dtype, str): 2888 if dtype.upper() in cls.Type.__members__: 2889 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2890 else: 2891 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2892 if data_type_exp is None: 2893 raise ValueError(f"Unparsable data type value: {dtype}") 2894 elif isinstance(dtype, DataType.Type): 2895 data_type_exp = DataType(this=dtype) 2896 elif isinstance(dtype, DataType): 2897 return dtype 2898 else: 2899 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2900 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2792 class Type(AutoName): 2793 CHAR = auto() 2794 NCHAR = auto() 2795 VARCHAR = auto() 2796 NVARCHAR = auto() 2797 TEXT = auto() 2798 MEDIUMTEXT = auto() 2799 LONGTEXT = auto() 2800 MEDIUMBLOB = auto() 2801 LONGBLOB = auto() 2802 BINARY = auto() 2803 VARBINARY = auto() 2804 INT = auto() 2805 UINT = auto() 2806 TINYINT = auto() 2807 UTINYINT = auto() 2808 SMALLINT = auto() 2809 USMALLINT = auto() 2810 BIGINT = auto() 2811 UBIGINT = auto() 2812 FLOAT = auto() 2813 DOUBLE = auto() 2814 DECIMAL = auto() 2815 BIT = auto() 2816 BOOLEAN = auto() 2817 JSON = auto() 2818 JSONB = auto() 2819 INTERVAL = auto() 2820 TIME = auto() 2821 TIMESTAMP = auto() 2822 TIMESTAMPTZ = auto() 2823 TIMESTAMPLTZ = auto() 2824 DATE = auto() 2825 DATETIME = auto() 2826 ARRAY = auto() 2827 MAP = auto() 2828 UUID = auto() 2829 GEOGRAPHY = auto() 2830 GEOMETRY = auto() 2831 STRUCT = auto() 2832 NULLABLE = auto() 2833 HLLSKETCH = auto() 2834 HSTORE = auto() 2835 SUPER = auto() 2836 SERIAL = auto() 2837 SMALLSERIAL = auto() 2838 BIGSERIAL = auto() 2839 XML = auto() 2840 UNIQUEIDENTIFIER = auto() 2841 MONEY = auto() 2842 SMALLMONEY = auto() 2843 ROWVERSION = auto() 2844 IMAGE = auto() 2845 VARIANT = auto() 2846 OBJECT = auto() 2847 INET = auto() 2848 NULL = auto() 2849 UNKNOWN = auto() # Sentinel value, useful for type annotation
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2954class AddConstraint(Expression): 2955 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2963class Binary(Expression): 2964 arg_types = {"this": True, "expression": True} 2965 2966 @property 2967 def left(self): 2968 return self.this 2969 2970 @property 2971 def right(self): 2972 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3019class Dot(Binary): 3020 @property 3021 def name(self) -> str: 3022 return self.expression.name 3023 3024 @classmethod 3025 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3026 """Build a Dot object with a sequence of expressions.""" 3027 if len(expressions) < 2: 3028 raise ValueError(f"Dot requires >= 2 expressions.") 3029 3030 a, b, *expressions = expressions 3031 dot = Dot(this=a, expression=b) 3032 3033 for expression in expressions: 3034 dot = Dot(this=dot, expression=expression) 3035 3036 return dot
3024 @classmethod 3025 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3026 """Build a Dot object with a sequence of expressions.""" 3027 if len(expressions) < 2: 3028 raise ValueError(f"Dot requires >= 2 expressions.") 3029 3030 a, b, *expressions = expressions 3031 dot = Dot(this=a, expression=b) 3032 3033 for expression in expressions: 3034 dot = Dot(this=dot, expression=expression) 3035 3036 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3162class Alias(Expression): 3163 arg_types = {"this": True, "alias": False} 3164 3165 @property 3166 def output_name(self): 3167 return self.alias
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3170class Aliases(Expression): 3171 arg_types = {"this": True, "expressions": True} 3172 3173 @property 3174 def aliases(self): 3175 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3194class In(Predicate): 3195 arg_types = { 3196 "this": True, 3197 "expressions": False, 3198 "query": False, 3199 "unnest": False, 3200 "field": False, 3201 "is_global": False, 3202 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3205class TimeUnit(Expression): 3206 """Automatically converts unit arg into a var.""" 3207 3208 arg_types = {"unit": False} 3209 3210 def __init__(self, **args): 3211 unit = args.get("unit") 3212 if isinstance(unit, (Column, Literal)): 3213 args["unit"] = Var(this=unit.name) 3214 elif isinstance(unit, Week): 3215 unit.set("this", Var(this=unit.this.name)) 3216 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3232class Func(Condition): 3233 """ 3234 The base class for all function expressions. 3235 3236 Attributes: 3237 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3238 treated as a variable length argument and the argument's value will be stored as a list. 3239 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3240 for this function expression. These values are used to map this node to a name during parsing 3241 as well as to provide the function's name during SQL string generation. By default the SQL 3242 name is set to the expression's class name transformed to snake case. 3243 """ 3244 3245 is_var_len_args = False 3246 3247 @classmethod 3248 def from_arg_list(cls, args): 3249 if cls.is_var_len_args: 3250 all_arg_keys = list(cls.arg_types) 3251 # If this function supports variable length argument treat the last argument as such. 3252 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3253 num_non_var = len(non_var_len_arg_keys) 3254 3255 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3256 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3257 else: 3258 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3259 3260 return cls(**args_dict) 3261 3262 @classmethod 3263 def sql_names(cls): 3264 if cls is Func: 3265 raise NotImplementedError( 3266 "SQL name is only supported by concrete function implementations" 3267 ) 3268 if "_sql_names" not in cls.__dict__: 3269 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3270 return cls._sql_names 3271 3272 @classmethod 3273 def sql_name(cls): 3274 return cls.sql_names()[0] 3275 3276 @classmethod 3277 def default_parser_mappings(cls): 3278 return {name: cls.from_arg_list for name in cls.sql_names()}
The base class for all function expressions.
Attributes:
- is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
- _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
3247 @classmethod 3248 def from_arg_list(cls, args): 3249 if cls.is_var_len_args: 3250 all_arg_keys = list(cls.arg_types) 3251 # If this function supports variable length argument treat the last argument as such. 3252 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3253 num_non_var = len(non_var_len_arg_keys) 3254 3255 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3256 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3257 else: 3258 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3259 3260 return cls(**args_dict)
3262 @classmethod 3263 def sql_names(cls): 3264 if cls is Func: 3265 raise NotImplementedError( 3266 "SQL name is only supported by concrete function implementations" 3267 ) 3268 if "_sql_names" not in cls.__dict__: 3269 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3270 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3289class Anonymous(Func): 3290 arg_types = {"this": True, "expressions": False} 3291 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3324class ArrayConcat(Func): 3325 arg_types = {"this": True, "expressions": False} 3326 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3337class ArrayFilter(Func): 3338 arg_types = {"this": True, "expression": True} 3339 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3374class Cast(Func): 3375 arg_types = {"this": True, "to": True} 3376 3377 @property 3378 def name(self) -> str: 3379 return self.this.name 3380 3381 @property 3382 def to(self): 3383 return self.args["to"] 3384 3385 @property 3386 def output_name(self): 3387 return self.name 3388 3389 def is_type(self, dtype: DataType.Type) -> bool: 3390 return self.to.is_type(dtype)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3401class Ceil(Func): 3402 arg_types = {"this": True, "decimals": False} 3403 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3406class Coalesce(Func): 3407 arg_types = {"this": True, "expressions": False} 3408 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3444class DateAdd(Func, TimeUnit): 3445 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3448class DateSub(Func, TimeUnit): 3449 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3452class DateDiff(Func, TimeUnit): 3453 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3454 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3461class DatetimeAdd(Func, TimeUnit): 3462 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3465class DatetimeSub(Func, TimeUnit): 3466 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3469class DatetimeDiff(Func, TimeUnit): 3470 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3473class DatetimeTrunc(Func, TimeUnit): 3474 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3501class TimestampAdd(Func, TimeUnit): 3502 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3505class TimestampSub(Func, TimeUnit): 3506 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3509class TimestampDiff(Func, TimeUnit): 3510 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3513class TimestampTrunc(Func, TimeUnit): 3514 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3517class TimeAdd(Func, TimeUnit): 3518 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3521class TimeSub(Func, TimeUnit): 3522 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3525class TimeDiff(Func, TimeUnit): 3526 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3533class DateFromParts(Func): 3534 _sql_names = ["DATEFROMPARTS"] 3535 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3574class ExponentialTimeDecayedAvg(AggFunc): 3575 arg_types = {"this": True, "time": False, "decay": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3582class Greatest(Func): 3583 arg_types = {"this": True, "expressions": False} 3584 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3607class IfNull(Func): 3608 arg_types = {"this": True, "expression": False} 3609 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3620class JSONObject(Func): 3621 arg_types = { 3622 "expressions": False, 3623 "null_handling": False, 3624 "unique_keys": False, 3625 "return_type": False, 3626 "format_json": False, 3627 "encoding": False, 3628 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3660class Levenshtein(Func): 3661 arg_types = { 3662 "this": True, 3663 "expression": False, 3664 "ins_cost": False, 3665 "del_cost": False, 3666 "sub_cost": False, 3667 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3707class Matches(Func): 3708 """Oracle/Snowflake decode. 3709 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm 3710 Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else) 3711 """ 3712 3713 arg_types = {"this": True, "expressions": True} 3714 is_var_len_args = True
Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3717class Max(AggFunc): 3718 arg_types = {"this": True, "expressions": False} 3719 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3722class Min(AggFunc): 3723 arg_types = {"this": True, "expressions": False} 3724 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3757class Quantiles(AggFunc): 3758 arg_types = {"parameters": True, "expressions": True} 3759 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3766class ApproxQuantile(Quantile): 3767 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3774class ReadCSV(Func): 3775 _sql_names = ["READ_CSV"] 3776 is_var_len_args = True 3777 arg_types = {"this": True, "expressions": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3780class Reduce(Func): 3781 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3784class RegexpExtract(Func): 3785 arg_types = { 3786 "this": True, 3787 "expression": True, 3788 "position": False, 3789 "occurrence": False, 3790 "group": False, 3791 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3842class StrPosition(Func): 3843 arg_types = { 3844 "this": True, 3845 "substr": True, 3846 "position": False, 3847 "instance": False, 3848 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3922class Trim(Func): 3923 arg_types = { 3924 "this": True, 3925 "expression": False, 3926 "position": False, 3927 "collation": False, 3928 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3931class TsOrDsAdd(Func, TimeUnit): 3932 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3957class UnixToTime(Func): 3958 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 3959 3960 SECONDS = Literal.string("seconds") 3961 MILLIS = Literal.string("millis") 3962 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3985class XMLTable(Func): 3986 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3997class Merge(Expression): 3998 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4001class When(Func): 4002 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4013def maybe_parse( 4014 sql_or_expression: ExpOrStr, 4015 *, 4016 into: t.Optional[IntoType] = None, 4017 dialect: DialectType = None, 4018 prefix: t.Optional[str] = None, 4019 copy: bool = False, 4020 **opts, 4021) -> Expression: 4022 """Gracefully handle a possible string or expression. 4023 4024 Example: 4025 >>> maybe_parse("1") 4026 (LITERAL this: 1, is_string: False) 4027 >>> maybe_parse(to_identifier("x")) 4028 (IDENTIFIER this: x, quoted: False) 4029 4030 Args: 4031 sql_or_expression: the SQL code string or an expression 4032 into: the SQLGlot Expression to parse into 4033 dialect: the dialect used to parse the input expressions (in the case that an 4034 input expression is a SQL string). 4035 prefix: a string to prefix the sql with before it gets parsed 4036 (automatically includes a space) 4037 copy: whether or not to copy the expression. 4038 **opts: other options to use to parse the input expressions (again, in the case 4039 that an input expression is a SQL string). 4040 4041 Returns: 4042 Expression: the parsed or given expression. 4043 """ 4044 if isinstance(sql_or_expression, Expression): 4045 if copy: 4046 return sql_or_expression.copy() 4047 return sql_or_expression 4048 4049 import sqlglot 4050 4051 sql = str(sql_or_expression) 4052 if prefix: 4053 sql = f"{prefix} {sql}" 4054 return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
Gracefully handle a possible string or expression.
Example:
>>> maybe_parse("1") (LITERAL this: 1, is_string: False) >>> maybe_parse(to_identifier("x")) (IDENTIFIER this: x, quoted: False)
Arguments:
- sql_or_expression: the SQL code string or an expression
- into: the SQLGlot Expression to parse into
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
- copy: whether or not to copy the expression.
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Expression: the parsed or given expression.
4200def union(left, right, distinct=True, dialect=None, **opts): 4201 """ 4202 Initializes a syntax tree from one UNION expression. 4203 4204 Example: 4205 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4206 'SELECT * FROM foo UNION SELECT * FROM bla' 4207 4208 Args: 4209 left (str | Expression): the SQL code string corresponding to the left-hand side. 4210 If an `Expression` instance is passed, it will be used as-is. 4211 right (str | Expression): the SQL code string corresponding to the right-hand side. 4212 If an `Expression` instance is passed, it will be used as-is. 4213 distinct (bool): set the DISTINCT flag if and only if this is true. 4214 dialect (str): the dialect used to parse the input expression. 4215 opts (kwargs): other options to use to parse the input expressions. 4216 Returns: 4217 Union: the syntax tree for the UNION expression. 4218 """ 4219 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4220 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4221 4222 return Union(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one UNION expression.
Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the syntax tree for the UNION expression.
4225def intersect(left, right, distinct=True, dialect=None, **opts): 4226 """ 4227 Initializes a syntax tree from one INTERSECT expression. 4228 4229 Example: 4230 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4231 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4232 4233 Args: 4234 left (str | Expression): the SQL code string corresponding to the left-hand side. 4235 If an `Expression` instance is passed, it will be used as-is. 4236 right (str | Expression): the SQL code string corresponding to the right-hand side. 4237 If an `Expression` instance is passed, it will be used as-is. 4238 distinct (bool): set the DISTINCT flag if and only if this is true. 4239 dialect (str): the dialect used to parse the input expression. 4240 opts (kwargs): other options to use to parse the input expressions. 4241 Returns: 4242 Intersect: the syntax tree for the INTERSECT expression. 4243 """ 4244 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4245 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4246 4247 return Intersect(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one INTERSECT expression.
Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the syntax tree for the INTERSECT expression.
4250def except_(left, right, distinct=True, dialect=None, **opts): 4251 """ 4252 Initializes a syntax tree from one EXCEPT expression. 4253 4254 Example: 4255 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4256 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4257 4258 Args: 4259 left (str | Expression): the SQL code string corresponding to the left-hand side. 4260 If an `Expression` instance is passed, it will be used as-is. 4261 right (str | Expression): the SQL code string corresponding to the right-hand side. 4262 If an `Expression` instance is passed, it will be used as-is. 4263 distinct (bool): set the DISTINCT flag if and only if this is true. 4264 dialect (str): the dialect used to parse the input expression. 4265 opts (kwargs): other options to use to parse the input expressions. 4266 Returns: 4267 Except: the syntax tree for the EXCEPT statement. 4268 """ 4269 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4270 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4271 4272 return Except(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one EXCEPT expression.
Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the syntax tree for the EXCEPT statement.
4275def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4276 """ 4277 Initializes a syntax tree from one or multiple SELECT expressions. 4278 4279 Example: 4280 >>> select("col1", "col2").from_("tbl").sql() 4281 'SELECT col1, col2 FROM tbl' 4282 4283 Args: 4284 *expressions: the SQL code string to parse as the expressions of a 4285 SELECT statement. If an Expression instance is passed, this is used as-is. 4286 dialect: the dialect used to parse the input expressions (in the case that an 4287 input expression is a SQL string). 4288 **opts: other options to use to parse the input expressions (again, in the case 4289 that an input expression is a SQL string). 4290 4291 Returns: 4292 Select: the syntax tree for the SELECT statement. 4293 """ 4294 return Select().select(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from one or multiple SELECT expressions.
Example:
>>> select("col1", "col2").from_("tbl").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4297def from_(*expressions, dialect=None, **opts) -> Select: 4298 """ 4299 Initializes a syntax tree from a FROM expression. 4300 4301 Example: 4302 >>> from_("tbl").select("col1", "col2").sql() 4303 'SELECT col1, col2 FROM tbl' 4304 4305 Args: 4306 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4307 SELECT statement. If an Expression instance is passed, this is used as-is. 4308 dialect (str): the dialect used to parse the input expression (in the case that the 4309 input expression is a SQL string). 4310 **opts: other options to use to parse the input expressions (again, in the case 4311 that the input expression is a SQL string). 4312 4313 Returns: 4314 Select: the syntax tree for the SELECT statement. 4315 """ 4316 return Select().from_(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4319def update( 4320 table: str | Table, 4321 properties: dict, 4322 where: t.Optional[ExpOrStr] = None, 4323 from_: t.Optional[ExpOrStr] = None, 4324 dialect: DialectType = None, 4325 **opts, 4326) -> Update: 4327 """ 4328 Creates an update statement. 4329 4330 Example: 4331 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4332 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4333 4334 Args: 4335 *properties: dictionary of properties to set which are 4336 auto converted to sql objects eg None -> NULL 4337 where: sql conditional parsed into a WHERE statement 4338 from_: sql statement parsed into a FROM statement 4339 dialect: the dialect used to parse the input expressions. 4340 **opts: other options to use to parse the input expressions. 4341 4342 Returns: 4343 Update: the syntax tree for the UPDATE statement. 4344 """ 4345 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4346 update_expr.set( 4347 "expressions", 4348 [ 4349 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4350 for k, v in properties.items() 4351 ], 4352 ) 4353 if from_: 4354 update_expr.set( 4355 "from", 4356 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4357 ) 4358 if isinstance(where, Condition): 4359 where = Where(this=where) 4360 if where: 4361 update_expr.set( 4362 "where", 4363 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4364 ) 4365 return update_expr
Creates an update statement.
Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
- *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
- where: sql conditional parsed into a WHERE statement
- from_: sql statement parsed into a FROM statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Update: the syntax tree for the UPDATE statement.
4368def delete( 4369 table: ExpOrStr, 4370 where: t.Optional[ExpOrStr] = None, 4371 returning: t.Optional[ExpOrStr] = None, 4372 dialect: DialectType = None, 4373 **opts, 4374) -> Delete: 4375 """ 4376 Builds a delete statement. 4377 4378 Example: 4379 >>> delete("my_table", where="id > 1").sql() 4380 'DELETE FROM my_table WHERE id > 1' 4381 4382 Args: 4383 where: sql conditional parsed into a WHERE statement 4384 returning: sql conditional parsed into a RETURNING statement 4385 dialect: the dialect used to parse the input expressions. 4386 **opts: other options to use to parse the input expressions. 4387 4388 Returns: 4389 Delete: the syntax tree for the DELETE statement. 4390 """ 4391 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4392 if where: 4393 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4394 if returning: 4395 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4396 return delete_expr
Builds a delete statement.
Example:
>>> delete("my_table", where="id > 1").sql() 'DELETE FROM my_table WHERE id > 1'
Arguments:
- where: sql conditional parsed into a WHERE statement
- returning: sql conditional parsed into a RETURNING statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Delete: the syntax tree for the DELETE statement.
4399def condition(expression, dialect=None, **opts) -> Condition: 4400 """ 4401 Initialize a logical condition expression. 4402 4403 Example: 4404 >>> condition("x=1").sql() 4405 'x = 1' 4406 4407 This is helpful for composing larger logical syntax trees: 4408 >>> where = condition("x=1") 4409 >>> where = where.and_("y=1") 4410 >>> Select().from_("tbl").select("*").where(where).sql() 4411 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4412 4413 Args: 4414 *expression (str | Expression): the SQL code string to parse. 4415 If an Expression instance is passed, this is used as-is. 4416 dialect (str): the dialect used to parse the input expression (in the case that the 4417 input expression is a SQL string). 4418 **opts: other options to use to parse the input expressions (again, in the case 4419 that the input expression is a SQL string). 4420 4421 Returns: 4422 Condition: the expression 4423 """ 4424 return maybe_parse( # type: ignore 4425 expression, 4426 into=Condition, 4427 dialect=dialect, 4428 **opts, 4429 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4432def and_(*expressions, dialect=None, **opts) -> And: 4433 """ 4434 Combine multiple conditions with an AND logical operator. 4435 4436 Example: 4437 >>> and_("x=1", and_("y=1", "z=1")).sql() 4438 'x = 1 AND (y = 1 AND z = 1)' 4439 4440 Args: 4441 *expressions (str | Expression): the SQL code strings to parse. 4442 If an Expression instance is passed, this is used as-is. 4443 dialect (str): the dialect used to parse the input expression. 4444 **opts: other options to use to parse the input expressions. 4445 4446 Returns: 4447 And: the new condition 4448 """ 4449 return _combine(expressions, And, dialect, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4452def or_(*expressions, dialect=None, **opts) -> Or: 4453 """ 4454 Combine multiple conditions with an OR logical operator. 4455 4456 Example: 4457 >>> or_("x=1", or_("y=1", "z=1")).sql() 4458 'x = 1 OR (y = 1 OR z = 1)' 4459 4460 Args: 4461 *expressions (str | Expression): the SQL code strings to parse. 4462 If an Expression instance is passed, this is used as-is. 4463 dialect (str): the dialect used to parse the input expression. 4464 **opts: other options to use to parse the input expressions. 4465 4466 Returns: 4467 Or: the new condition 4468 """ 4469 return _combine(expressions, Or, dialect, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4472def not_(expression, dialect=None, **opts) -> Not: 4473 """ 4474 Wrap a condition with a NOT operator. 4475 4476 Example: 4477 >>> not_("this_suit='black'").sql() 4478 "NOT this_suit = 'black'" 4479 4480 Args: 4481 expression (str | Expression): the SQL code strings to parse. 4482 If an Expression instance is passed, this is used as-is. 4483 dialect (str): the dialect used to parse the input expression. 4484 **opts: other options to use to parse the input expressions. 4485 4486 Returns: 4487 Not: the new condition 4488 """ 4489 this = condition( 4490 expression, 4491 dialect=dialect, 4492 **opts, 4493 ) 4494 return Not(this=_wrap_operator(this))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Not: the new condition
4514def to_identifier(name, quoted=None): 4515 """Builds an identifier. 4516 4517 Args: 4518 name: The name to turn into an identifier. 4519 quoted: Whether or not force quote the identifier. 4520 4521 Returns: 4522 The identifier ast node. 4523 """ 4524 4525 if name is None: 4526 return None 4527 4528 if isinstance(name, Identifier): 4529 identifier = name 4530 elif isinstance(name, str): 4531 identifier = Identifier( 4532 this=name, 4533 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4534 ) 4535 else: 4536 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4537 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
Returns:
The identifier ast node.
4543def to_interval(interval: str | Literal) -> Interval: 4544 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4545 if isinstance(interval, Literal): 4546 if not interval.is_string: 4547 raise ValueError("Invalid interval string.") 4548 4549 interval = interval.this 4550 4551 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4552 4553 if not interval_parts: 4554 raise ValueError("Invalid interval string.") 4555 4556 return Interval( 4557 this=Literal.string(interval_parts.group(1)), 4558 unit=Var(this=interval_parts.group(2)), 4559 )
Builds an interval expression from a string like '1 day' or '5 months'.
4572def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4573 """ 4574 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4575 If a table is passed in then that table is returned. 4576 4577 Args: 4578 sql_path: a `[catalog].[schema].[table]` string. 4579 4580 Returns: 4581 A table expression. 4582 """ 4583 if sql_path is None or isinstance(sql_path, Table): 4584 return sql_path 4585 if not isinstance(sql_path, str): 4586 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4587 4588 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4589 return Table(this=table_name, db=db, catalog=catalog, **kwargs)
Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional.
If a table is passed in then that table is returned.
Arguments:
- sql_path: a
[catalog].[schema].[table]string.
Returns:
A table expression.
4592def to_column(sql_path: str | Column, **kwargs) -> Column: 4593 """ 4594 Create a column from a `[table].[column]` sql path. Schema is optional. 4595 4596 If a column is passed in then that column is returned. 4597 4598 Args: 4599 sql_path: `[table].[column]` string 4600 Returns: 4601 Table: A column expression 4602 """ 4603 if sql_path is None or isinstance(sql_path, Column): 4604 return sql_path 4605 if not isinstance(sql_path, str): 4606 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4607 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore
Create a column from a [table].[column] sql path. Schema is optional.
If a column is passed in then that column is returned.
Arguments:
- sql_path:
[table].[column]string
Returns:
Table: A column expression
4610def alias_( 4611 expression: ExpOrStr, 4612 alias: str | Identifier, 4613 table: bool | t.Sequence[str | Identifier] = False, 4614 quoted: t.Optional[bool] = None, 4615 dialect: DialectType = None, 4616 **opts, 4617): 4618 """Create an Alias expression. 4619 4620 Example: 4621 >>> alias_('foo', 'bar').sql() 4622 'foo AS bar' 4623 4624 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4625 '(SELECT 1, 2) AS bar(a, b)' 4626 4627 Args: 4628 expression: the SQL code strings to parse. 4629 If an Expression instance is passed, this is used as-is. 4630 alias: the alias name to use. If the name has 4631 special characters it is quoted. 4632 table: Whether or not to create a table alias, can also be a list of columns. 4633 quoted: whether or not to quote the alias 4634 dialect: the dialect used to parse the input expression. 4635 **opts: other options to use to parse the input expressions. 4636 4637 Returns: 4638 Alias: the aliased expression 4639 """ 4640 exp = maybe_parse(expression, dialect=dialect, **opts) 4641 alias = to_identifier(alias, quoted=quoted) 4642 4643 if table: 4644 table_alias = TableAlias(this=alias) 4645 exp.set("alias", table_alias) 4646 4647 if not isinstance(table, bool): 4648 for column in table: 4649 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4650 4651 return exp 4652 4653 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4654 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4655 # for the complete Window expression. 4656 # 4657 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4658 4659 if "alias" in exp.arg_types and not isinstance(exp, Window): 4660 exp = exp.copy() 4661 exp.set("alias", alias) 4662 return exp 4663 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
4666def subquery(expression, alias=None, dialect=None, **opts): 4667 """ 4668 Build a subquery expression. 4669 4670 Example: 4671 >>> subquery('select x from tbl', 'bar').select('x').sql() 4672 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4673 4674 Args: 4675 expression (str | Expression): the SQL code strings to parse. 4676 If an Expression instance is passed, this is used as-is. 4677 alias (str | Expression): the alias name to use. 4678 dialect (str): the dialect used to parse the input expression. 4679 **opts: other options to use to parse the input expressions. 4680 4681 Returns: 4682 Select: a new select with the subquery expression included 4683 """ 4684 4685 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4686 return Select().from_(expression, dialect=dialect, **opts)
Build a subquery expression.
Example:
>>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias (str | Expression): the alias name to use.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Select: a new select with the subquery expression included
4689def column( 4690 col: str | Identifier, 4691 table: t.Optional[str | Identifier] = None, 4692 db: t.Optional[str | Identifier] = None, 4693 catalog: t.Optional[str | Identifier] = None, 4694 quoted: t.Optional[bool] = None, 4695) -> Column: 4696 """ 4697 Build a Column. 4698 4699 Args: 4700 col: column name 4701 table: table name 4702 db: db name 4703 catalog: catalog name 4704 quoted: whether or not to force quote each part 4705 Returns: 4706 Column: column instance 4707 """ 4708 return Column( 4709 this=to_identifier(col, quoted=quoted), 4710 table=to_identifier(table, quoted=quoted), 4711 db=to_identifier(db, quoted=quoted), 4712 catalog=to_identifier(catalog, quoted=quoted), 4713 )
Build a Column.
Arguments:
- col: column name
- table: table name
- db: db name
- catalog: catalog name
- quoted: whether or not to force quote each part
Returns:
Column: column instance
4716def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4717 """Cast an expression to a data type. 4718 4719 Example: 4720 >>> cast('x + 1', 'int').sql() 4721 'CAST(x + 1 AS INT)' 4722 4723 Args: 4724 expression: The expression to cast. 4725 to: The datatype to cast to. 4726 4727 Returns: 4728 A cast node. 4729 """ 4730 expression = maybe_parse(expression, **opts) 4731 return Cast(this=expression, to=DataType.build(to, **opts))
Cast an expression to a data type.
Example:
>>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Arguments:
- expression: The expression to cast.
- to: The datatype to cast to.
Returns:
A cast node.
4734def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4735 """Build a Table. 4736 4737 Args: 4738 table (str | Expression): column name 4739 db (str | Expression): db name 4740 catalog (str | Expression): catalog name 4741 4742 Returns: 4743 Table: table instance 4744 """ 4745 return Table( 4746 this=to_identifier(table, quoted=quoted), 4747 db=to_identifier(db, quoted=quoted), 4748 catalog=to_identifier(catalog, quoted=quoted), 4749 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4750 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
4753def values( 4754 values: t.Iterable[t.Tuple[t.Any, ...]], 4755 alias: t.Optional[str] = None, 4756 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4757) -> Values: 4758 """Build VALUES statement. 4759 4760 Example: 4761 >>> values([(1, '2')]).sql() 4762 "VALUES (1, '2')" 4763 4764 Args: 4765 values: values statements that will be converted to SQL 4766 alias: optional alias 4767 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4768 If either are provided then an alias is also required. 4769 If a dictionary is provided then the first column of the values will be casted to the expected type 4770 in order to help with type inference. 4771 4772 Returns: 4773 Values: the Values expression object 4774 """ 4775 if columns and not alias: 4776 raise ValueError("Alias is required when providing columns") 4777 table_alias = ( 4778 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4779 if columns 4780 else TableAlias(this=to_identifier(alias) if alias else None) 4781 ) 4782 expressions = [convert(tup) for tup in values] 4783 if columns and isinstance(columns, dict): 4784 types = list(columns.values()) 4785 expressions[0].set( 4786 "expressions", 4787 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4788 ) 4789 return Values( 4790 expressions=expressions, 4791 alias=table_alias, 4792 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:
Values: the Values expression object
4795def var(name: t.Optional[ExpOrStr]) -> Var: 4796 """Build a SQL variable. 4797 4798 Example: 4799 >>> repr(var('x')) 4800 '(VAR this: x)' 4801 4802 >>> repr(var(column('x', table='y'))) 4803 '(VAR this: x)' 4804 4805 Args: 4806 name: The name of the var or an expression who's name will become the var. 4807 4808 Returns: 4809 The new variable node. 4810 """ 4811 if not name: 4812 raise ValueError("Cannot convert empty name into var.") 4813 4814 if isinstance(name, Expression): 4815 name = name.name 4816 return Var(this=name)
Build a SQL variable.
Example:
>>> repr(var('x')) '(VAR this: x)'>>> repr(var(column('x', table='y'))) '(VAR this: x)'
Arguments:
- name: The name of the var or an expression who's name will become the var.
Returns:
The new variable node.
4819def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4820 """Build ALTER TABLE... RENAME... expression 4821 4822 Args: 4823 old_name: The old name of the table 4824 new_name: The new name of the table 4825 4826 Returns: 4827 Alter table expression 4828 """ 4829 old_table = to_table(old_name) 4830 new_table = to_table(new_name) 4831 return AlterTable( 4832 this=old_table, 4833 actions=[ 4834 RenameTable(this=new_table), 4835 ], 4836 )
Build ALTER TABLE... RENAME... expression
Arguments:
- old_name: The old name of the table
- new_name: The new name of the table
Returns:
Alter table expression
4839def convert(value) -> Expression: 4840 """Convert a python value into an expression object. 4841 4842 Raises an error if a conversion is not possible. 4843 4844 Args: 4845 value (Any): a python object 4846 4847 Returns: 4848 Expression: the equivalent expression object 4849 """ 4850 if isinstance(value, Expression): 4851 return value 4852 if value is None: 4853 return NULL 4854 if isinstance(value, bool): 4855 return Boolean(this=value) 4856 if isinstance(value, str): 4857 return Literal.string(value) 4858 if isinstance(value, float) and math.isnan(value): 4859 return NULL 4860 if isinstance(value, numbers.Number): 4861 return Literal.number(value) 4862 if isinstance(value, tuple): 4863 return Tuple(expressions=[convert(v) for v in value]) 4864 if isinstance(value, list): 4865 return Array(expressions=[convert(v) for v in value]) 4866 if isinstance(value, dict): 4867 return Map( 4868 keys=[convert(k) for k in value], 4869 values=[convert(v) for v in value.values()], 4870 ) 4871 if isinstance(value, datetime.datetime): 4872 datetime_literal = Literal.string( 4873 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4874 ) 4875 return TimeStrToTime(this=datetime_literal) 4876 if isinstance(value, datetime.date): 4877 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4878 return DateStrToDate(this=date_literal) 4879 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value (Any): a python object
Returns:
Expression: the equivalent expression object
4882def replace_children(expression, fun, *args, **kwargs): 4883 """ 4884 Replace children of an expression with the result of a lambda fun(child) -> exp. 4885 """ 4886 for k, v in expression.args.items(): 4887 is_list_arg = type(v) is list 4888 4889 child_nodes = v if is_list_arg else [v] 4890 new_child_nodes = [] 4891 4892 for cn in child_nodes: 4893 if isinstance(cn, Expression): 4894 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4895 new_child_nodes.append(child_node) 4896 child_node.parent = expression 4897 child_node.arg_key = k 4898 else: 4899 new_child_nodes.append(cn) 4900 4901 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
Replace children of an expression with the result of a lambda fun(child) -> exp.
4904def column_table_names(expression): 4905 """ 4906 Return all table names referenced through columns in an expression. 4907 4908 Example: 4909 >>> import sqlglot 4910 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4911 ['c', 'a'] 4912 4913 Args: 4914 expression (sqlglot.Expression): expression to find table names 4915 4916 Returns: 4917 list: A list of unique names 4918 """ 4919 return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) ['c', 'a']
Arguments:
- expression (sqlglot.Expression): expression to find table names
Returns:
list: A list of unique names
4922def table_name(table) -> str: 4923 """Get the full name of a table as a string. 4924 4925 Args: 4926 table (exp.Table | str): table expression node or string. 4927 4928 Examples: 4929 >>> from sqlglot import exp, parse_one 4930 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 4931 'a.b.c' 4932 4933 Returns: 4934 The table name. 4935 """ 4936 4937 table = maybe_parse(table, into=Table) 4938 4939 if not table: 4940 raise ValueError(f"Cannot parse {table}") 4941 4942 return ".".join( 4943 part 4944 for part in ( 4945 table.text("catalog"), 4946 table.text("db"), 4947 table.name, 4948 ) 4949 if part 4950 )
Get the full name of a table as a string.
Arguments:
- table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns:
The table name.
4953def replace_tables(expression, mapping): 4954 """Replace all tables in expression according to the mapping. 4955 4956 Args: 4957 expression (sqlglot.Expression): expression node to be transformed and replaced. 4958 mapping (Dict[str, str]): mapping of table names. 4959 4960 Examples: 4961 >>> from sqlglot import exp, parse_one 4962 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 4963 'SELECT * FROM c' 4964 4965 Returns: 4966 The mapped expression. 4967 """ 4968 4969 def _replace_tables(node): 4970 if isinstance(node, Table): 4971 new_name = mapping.get(table_name(node)) 4972 if new_name: 4973 return to_table( 4974 new_name, 4975 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 4976 ) 4977 return node 4978 4979 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
4982def replace_placeholders(expression, *args, **kwargs): 4983 """Replace placeholders in an expression. 4984 4985 Args: 4986 expression (sqlglot.Expression): expression node to be transformed and replaced. 4987 args: positional names that will substitute unnamed placeholders in the given order. 4988 kwargs: keyword arguments that will substitute named placeholders. 4989 4990 Examples: 4991 >>> from sqlglot import exp, parse_one 4992 >>> replace_placeholders( 4993 ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" 4994 ... ).sql() 4995 'SELECT * FROM foo WHERE a = b' 4996 4997 Returns: 4998 The mapped expression. 4999 """ 5000 5001 def _replace_placeholders(node, args, **kwargs): 5002 if isinstance(node, Placeholder): 5003 if node.name: 5004 new_name = kwargs.get(node.name) 5005 if new_name: 5006 return to_identifier(new_name) 5007 else: 5008 try: 5009 return to_identifier(next(args)) 5010 except StopIteration: 5011 pass 5012 return node 5013 5014 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo" ... ).sql() 'SELECT * FROM foo WHERE a = b'
Returns:
The mapped expression.
5017def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression: 5018 """Transforms an expression by expanding all referenced sources into subqueries. 5019 5020 Examples: 5021 >>> from sqlglot import parse_one 5022 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5023 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5024 5025 Args: 5026 expression: The expression to expand. 5027 sources: A dictionary of name to Subqueryables. 5028 copy: Whether or not to copy the expression during transformation. Defaults to True. 5029 5030 Returns: 5031 The transformed expression. 5032 """ 5033 5034 def _expand(node: Expression): 5035 if isinstance(node, Table): 5036 name = table_name(node) 5037 source = sources.get(name) 5038 if source: 5039 subquery = source.subquery(node.alias or name) 5040 subquery.comments = [f"source: {name}"] 5041 return subquery 5042 return node 5043 5044 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5047def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5048 """ 5049 Returns a Func expression. 5050 5051 Examples: 5052 >>> func("abs", 5).sql() 5053 'ABS(5)' 5054 5055 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5056 'CAST(5 AS DOUBLE)' 5057 5058 Args: 5059 name: the name of the function to build. 5060 args: the args used to instantiate the function of interest. 5061 dialect: the source dialect. 5062 kwargs: the kwargs used to instantiate the function of interest. 5063 5064 Note: 5065 The arguments `args` and `kwargs` are mutually exclusive. 5066 5067 Returns: 5068 An instance of the function of interest, or an anonymous function, if `name` doesn't 5069 correspond to an existing `sqlglot.expressions.Func` class. 5070 """ 5071 if args and kwargs: 5072 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5073 5074 from sqlglot.dialects.dialect import Dialect 5075 5076 converted = [convert(arg) for arg in args] 5077 kwargs = {key: convert(value) for key, value in kwargs.items()} 5078 5079 parser = Dialect.get_or_raise(dialect)().parser() 5080 from_args_list = parser.FUNCTIONS.get(name.upper()) 5081 5082 if from_args_list: 5083 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5084 else: 5085 kwargs = kwargs or {"expressions": converted} 5086 function = Anonymous(this=name, **kwargs) 5087 5088 for error_message in function.error_messages(converted): 5089 raise ValueError(error_message) 5090 5091 return function
Returns a Func expression.
Examples:
>>> func("abs", 5).sql() 'ABS(5)'>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 'CAST(5 AS DOUBLE)'
Arguments:
- name: the name of the function to build.
- args: the args used to instantiate the function of interest.
- dialect: the source dialect.
- kwargs: the kwargs used to instantiate the function of interest.
Note:
The arguments
argsandkwargsare mutually exclusive.
Returns:
An instance of the function of interest, or an anonymous function, if
namedoesn't correspond to an existingsqlglot.expressions.Funcclass.
5094def true(): 5095 """ 5096 Returns a true Boolean expression. 5097 """ 5098 return Boolean(this=True)
Returns a true Boolean expression.
5101def false(): 5102 """ 5103 Returns a false Boolean expression. 5104 """ 5105 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.